In we got acquainted with the basic Termux commands, set up an SSH connection with the PC, learned how to create aliases, and installed several useful utilities. This time we will take a step further; we will:
- learn about Termux:API
- install Python and nano, and write a "Hello, world!" in Python
- learn about bash scripts, and write a script using Termux:API
- using a bash script, Termux:API, and Python, we will write a simple program
Since we now understand what the entered commands do, from the next step onward I won't describe each action in detail, but I will clarify where difficulties may arise.
I often use aliases, so the abbreviations used in this part are shown here:
alias updg='apt update && apt upgrade'
alias py='python'The plan is ready, let's get started! And of course, don't forget about the 'magic Tab' ().
Step 4
Diving into the Termux:API rabbit hole
API, how much meaning this word holds for the heart of a coder
If we don't touch on the topic of Termux:API, all our steps could be reduced to a simple retelling of some brochure like 'Linux for Dummies', as noted in the comments to the first part.
First, let's install Termux:API from the Google Play Market (afterwards, it won't hurt to restart Termux):

Next, we need to install the API package in the Termux console:
updg # Don't forget about aliases
apt install termux-apiFor experiments, I am using Android 5.1.1; for Android 7 users, you need to 'protect' Termux:API by going to 'Settings' > 'Protected apps', otherwise API calls like termux-battery-status, will hang. (See )
Now let's get to know the acquired capabilities better. The most up-to-date and detailed description of Termux:API can be found at . I will try to select the most illustrative and interesting examples that will help build your skills for independent work later.
Several examples of Termux:API
- termux-battery-status
Returns battery status

- termux-brightness
Sets screen brightness from 0 to 255

- termux-toast
Displays a temporary popup notification

- termux-torch
Turns on the flashlight

- termux-wifi-scaninfo
Returns information about the last Wi-Fi network scan

It is not hard to notice that the returned values are strings, dictionaries, lists of dictionaries, in general, data types that Python works with perfectly, so the next step is to install it.
Step 5
Let's install Python and nano
To install Python, type in the terminal:
updg
apt install python
apt install python2Now we have Python 2 and 3 installed.
During the work on the article, I discovered another text editor, nano, which I like more than vim, so let's install it:
apt install nanoIt is easier to use than vim, and nano has a more user-friendly interface. On Android devices, vim is still more convenient.
HelloWorld in Python on Termux
In general, this point could have been skipped, but installing Python in Termux and not writing HelloWorld seems like a faux pas to me.
I am not aiming to teach anyone Python, so those unfamiliar can just copy the code (or start studying independently, as there is plenty of literature available), while those who know can create something themselves. Meanwhile, I will also show a way to input text in the terminal without an editor.
cat >hello-world.py
# If you do not specify a source (reminding you cat 1.txt > 2.txt)
# then cat will take data from the standard input,
# in simpler terms, what you type on the keyboard.
str = 'Hello, world!' # assigning the value "Hello, world!" to the variable str
print (str) # displaying the value from the variable str on the screen
# Ctrl + D to finish input and save the file (hello-world.py)
py hello-world.py # running the file (py is an alias for python)
If during input you did not notice an error and already pressed Enter, you cannot move to the previous line; to do this, finish the input by pressing Ctrl + D (you can also interrupt it with Ctrl + Z) and repeat everything from the beginning. Since we used '>', the file will be completely overwritten. For this reason, I do not recommend using this method of input if you are not sure you will write the code correctly the first time.
Step 6
Bash scripts
Bash scripts are a wonderful way to automate tasks in the terminal. A script is a file with a .sh extension (the extension is not mandatory) containing a set of terminal commands, some of which we have already learned. Here is , everything should work, but note that this list is for "full" Linux, not for Termux, and here is simply .
Using scripts, you can automate almost all monotonous tasks. Let's write a simple bash script that outputs a value from a variable created by the script itself. I'll use cat again, but you can use a regular text editor, and those eager to practice can use echo.
cat >test.sh
export str="Hello, Habr!"
# export creates a variable str
# and assigns it the value "Hello, Habr!"
# Do not put spaces before or after ‘=’
echo $str # To access variables, put ‘$’ before them
# Ctrl + D
# ./test.sh to run the script, but if you do it now, there will be an error
# to avoid the error, you need to make the test.sh file executable
chmod +x test.sh
# chmod changes access rights (+ add / - remove)
# ‘+x’ means we are making the file executable
./test.sh # We run our script
Bash script with Termux:API
Let's write something different from the infamous HelloWorlds, but equally useless. Our script will:
- execute the API termux-battery-status request
- save the obtained data in the file test.txt
- output the data from the file to the screen
- execute the previously written program hello-world.py
- write the data received from the program into the file test.txt
- output the data from the file to the screen
- copy data from the file to the clipboard
- output the clipboard content to the screen
- display a popup message with the data from the clipboard
First, let's create a working folder and copy hello-world.py there as test.py. We'll create the files test.sh and test.txt in this folder:
mkdir bashscript
cat hello-world.py >> bashscript/test.py
cd bashscript/
touch test.sh test.txt # touch creates files
chmod +x test.shNow let's write the script into test.sh using any convenient method:
#!/bin/bash
# В начале каждого скрипта принято ставить #! (называется шебанг)
# после идет указание на шелл для которой написан скрипт
clear # очистим окно терминала
termux-battery-status > test.txt # пункты 1 и 2 из намеченного функционала
cat test.txt # пункт 3
python test.py > test.txt # пункт 4 и 5
cat test.txt # пункт 6
cat test.txt | termux-clipboard-set # пункт 7
# | это конвейер. переносит данные с выхода одного потока на вход другого
termux-clipboard-get # пункт 8
termux-clipboard-get | termux-toast # пункт 9Now, in the bashscript folder, we write ./test.sh and watch in the terminal on the Android device:

We have written the planned bash script. You can enhance its output with progress information for each action (using echo), which I'll leave for the readers.
Step 7
Let's do something useful
Relatively useful
Formulate the technical specifications
The application should place a random string from a file into the clipboard upon startup and notify this with a popup message.
We'll base it on a bash script, extracting a random string from the file using a Python subroutine. Let's outline the script's plan:
- Run the subroutine
- Copy the output of the subprogram to the clipboard
- Display a popup message
Let's define the names of the application's directory and files:
- folder rndstr in the home directory
- source — the file from which we will take the lines
- rndstr.py — a subprogram that outputs a random line from the source file to the console
- rndstr.sh — the script file
Create the application's directory and move into it to create the files there.
The first two steps of the script plan can be combined into a pipeline, ultimately using Termux:API we get:
#!/bin/bash
python ~/rndstr/rndstr.py | termux-clipboard-set # 1 и 2 пункты плана работы
termux-toast "OK" # 3 пункт. Выводим всплывающее сообщение "ОК"You can place any text logically divided into lines in the source file; I decided to include quotes:
Listing of the source file
Sincerity is not truth. L. Lavelle
Endure and restrain yourself. Epictetus
Only what is selfless is noble. J. La Bruyère
Be wisely daring. B. Gracian
Kindness is better than beauty. G. Heine
For great deeds, tireless perseverance is essential. F. Voltaire
If you want to be always please, serve yourself. B. Franklin
Excessive modesty is nothing but hidden pride. A. Chenier
Very intelligent people start to be distrusted when they show embarrassment. F. Nietzsche
Poverty indicates a lack of means, not a lack of nobility. D. Boccaccio
One must beware of taking modesty to the point of humiliation. A. Bakihanov
He who renounces much can afford much. J. Chardon
When we are paid for a noble act, it is taken from us. N. Chamfort
Not receiving at all is not scary, but losing what one received is painful. Claudius Aelian
It is easier to patiently endure that which we cannot change. Horace
You tire of waiting, but how much worse would it be if there were nothing left to wait for. B. Shaw
Everything comes in time if people know how to wait. F. Rabelais
With our patience, we can achieve more than with force. E. Burke
We must learn to endure what cannot be avoided. M. Montaigne
He who is bold in deed will not be frightened by words. Sophocles
I do not like to fight; I like to win. B. Shaw
A cornered and pressed cat turns into a tiger. M. Cervantes
A worthy person does not follow in the footsteps of others. Confucius
A great mind will demonstrate its strength not only in the ability to think, but in the ability to live. R. Emerson
Fame is an unprofitable commodity. It is expensive and poorly maintained. O. Balzac
Restraint and appropriateness in conversations are worth more than eloquence. F. Bacon
He who cannot be silent cannot speak. Seneca the Younger
Good manners consist of small sacrifices. F. Chesterfield
A good person is not one who can do good, but one who cannot do evil. V. Klyuchevsky
Do not make irrevocable judgments! Augustine
Nothing too much! SolonWe need to create a subprogram that extracts a random string from the source file.
Let's outline the algorithm for the subprogram's operation:
- Open the source file
- Count the number of lines in the opened file
- Close the file (there's no need to keep it open for longer than necessary)
- Generate a random integer within the number of lines in the source file
- Open the source file
- Output the line corresponding to the generated number
- Close the file
Implementing the algorithm in Python (I'm writing for Python 3.7):
import random # import for generating random numbers
import os # for getting the path
path = os.path.abspath(__file__) # get the direct path to the file rndstr.py
path = os.path.dirname(path) # convert to the directory path
path = path + 'source' # convert to the path for the source file
f = open(path) # open the file
i = 0 # reset the counter
for str in f: i+=1 # count the lines in the file
f.close # close the file
j = int(round(i * random.random())) # generate a random integer from 0 to i
f = open(path) # open the file
i = 0 # reset the counter
for str in f: # iterate through the lines from the file
if i == j: # if the line counter equals the generated number
print (str, end='') # output the line without a new line
break # exit the loop
i+=1 # increment the counter by 1
f.close # close the fileAfter the files are created and written, execution permissions need to be granted to the file rndstr.sh, and create an alias for quick execution.
alias rnst="~/rndstr/rndstr.sh"Now by typing in the terminal rnst we'll get a random aphorism in the clipboard, which, for example, can be used in correspondence.
Well, we've written something useful, relatively useful.
P.s.
I intentionally did not provide screenshots in the last step and did not elaborate on some actions, only outlining the contents of the files, so that readers would have the opportunity to work independently.
I think it makes sense to conclude this "Termux step by step". Of course, these are just the very first steps, but now you can move forward on your own.
Initially, I planned to show how to use nmap, sqlmap in this series, but there are already many articles on this topic without me. If there's a desire for me to continue the "Termux step by step" series, there's a survey below, and in the comments, you can suggest what else to write about.
Only registered users can participate in the survey. , please.
Continue "Termux step by step"?
Yes
No
2 users have voted. There are no abstentions.
Source: habr.com





