Termux step by step (Part 2)

В last part we got acquainted with the basic commands of Termux, set up an SSH connection to a PC, learned how to create alias's and installed several useful utilities. This time we have to step even further, we are with you:

  • learn about Termux:API
  • install Python and nano, and write "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 input commands do, then from the next step I will not describe each action in such detail, but where there may be difficulties, I will definitely explain.

I use aliases a lot, so the abbreviations used in this part are shown here:

alias updg='apt update && apt upgrade'
alias py='python'

The plan is ready, you can start! And of course, do not forget about the "magic Tab" (See Part 1).

Step 4

Diving Down the Termux:API Rabbit Hole

API how much has merged in this word for the coder's heart

If we do not touch on the topic of Termux: API, then all our steps could be reduced to a simple retelling of some brochure like "Linux for Dummies", as was rightly noted in the comments to the first part.

First, install Termux:API from the Google Play Market (it doesn't hurt to restart Termux afterwards):

Termux step by step (Part 2)

Next, we need to install the API package in the Termux console:

updg # Не забываем про alias’ы
apt install termux-api

For experimentation I'm using Android 5.1.1, for Android 7 owners need to "protect" Termux: API by going to 'Settings' > 'Protected Apps', otherwise API calls like termux-battery-status, will hang. (Cm. project wiki)

Now it is worth taking a closer look at the acquired opportunities. The latest and most detailed description of Termux:API can be found at project wiki. I will try to choose the most visual and interesting, which will allow me to fill my hand for independent work in the future.

Some Termux:API examples

  • termux-battery-status
    Returns the state of the battery
    Termux step by step (Part 2)
  • termux-brightness
    Sets the brightness of the screen from 0 to 255
    Termux step by step (Part 2)
  • termux-toast
    Shows a temporary toast notification
    Termux step by step (Part 2)
  • termux-torch
    Includes flashlight
    Termux step by step (Part 2)
  • termux-wifi-scaninfo
    Returns information about the last scan of Wi-Fi networks
    Termux step by step (Part 2)

It's easy to see that the return values ​​are strings, dictionaries, lists of dictionaries, in general, data types that Python works great with, so the next step is to set it up.

Step 5

Install Python and nano

To install Python, write in the terminal:

updg
apt install python
apt install python2

We now have 2 and 3 Python installed.

While working on the article, I discovered another nano text editor that I liked more than vim, let's install it:

apt install nano

It's easier to use than vim, and nano has a more user-friendly interface. On an Android device, vim is still more convenient.

HelloWorld in Python at Termux

By and large, it was possible to do without this item, but putting Python in Termux and not writing HelloWorld, in my opinion, is bad manners.

I do not aim to teach anyone Python, so those who do not know can simply copy the code (or start learning on their own, since there is enough literature), and those who know can make something themselves. And I'll "under the guise" still show a way to enter text in the terminal without an editor.

cat >hello-world.py     
# Если не указывать источник (напоминаю cat 1.txt > 2.txt)
# то cat будет брать данные из стандартного потока ввода,
# проще говоря вводимое с клавиатуры.

str = ‘Hello, world!’ # присваиваем переменной str значение "Hello, world!"
print (str) # выводим на экран значение из переменной str

# Ctrl + D закончить ввод и записать файл (hello-world.py)

py hello-world.py # запускаем файл (py это alias от python)

Termux step by step (Part 2)

If you didn’t notice an error during the input process and already pressed Enter, then you won’t be able to go to the line above, to do this, end the input by pressing Ctrl + D (you can generally interrupt Ctrl + Z) and repeat everything from the beginning. Since we used '>' then the file will be completely overwritten. For this reason, I do not recommend using this input method unless you are sure that you will write the code immediately without errors.

Step 6

Bash scripts

Bash scripts are a great way to automate your terminal work. The script is a file with the .sh extension (the extension is optional) containing a set of terminal commands, some of which we have already studied. Here list of most commands, everything should work, but note that this is a list for "adult" Linux, not Termux, but just great material on bash scripts.

With the help of scripts, you can automate almost all monotonous actions. Let's write the simplest bash script that displays the value from the variable he created, I'll use cat again, you can use a normal text editor, and those who especially want to train themselves can use echo.

cat >test.sh

export str="Привет, Хабр!"
# export создает переменную str
# и присваивает ей значение "Привет, Хабр!"
# Не ставьте пробелы до и после ‘=’

echo $str # Для обращения к переменным перед ними ставится ‘$’

# Ctrl + D

# ./test.sh для запуска скрипта, но если это сделать сейчас то будет ошибка
# для избавления от ошибки нужно сделать файл test.sh исполняемым

chmod +x test.sh
# chmod изменяет права доступа (+ добавить / - убрать)
# ‘+x’ означает что мы делаем файл исполняемым

./test.sh # Запускаем выполнение нашего скрипта

Termux step by step (Part 2)

Bash script with Termux:API

Let's write something different from the notorious HelloWorlds, but just as useless. Our script will be:

  1. execute the termux-battery-status API request
  2. save the received data to the file test.txt
  3. print data from a file to the screen
  4. execute the previously written hello-world.py program
  5. write the data received from the program to the file test.txt
  6. print data from a file to the screen
  7. move data from file to clipboard
  8. display the contents of the clipboard
  9. display a popup message with data from the clipboard

First, create a folder for work and copy hello-world.py there as test.py, create test.sh and test.txt files in this folder:

mkdir bashscript

cat hello-world.py >> bashscript/test.py

cd bashscript/

touch test.sh test.txt # touch создает файлы

chmod +x test.sh

Now, in any convenient way, write the script to the test.sh file:

#!/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 # пункт 9

Now, being in the bashscript folder, we write ./test.sh we observe in the terminal on the Android device:

Termux step by step (Part 2)

So we wrote the planned bash script. You can dilute it with the output to the console of information on the execution of each action (using echo), I will leave this for the readers.

Step 7

Let's do something useful

Relatively useful

Let's formulate the terms of reference
After launch, the application should place a random line from the file on the clipboard and notify about it with a pop-up message.

We will take a bash script as a basis, we will extract a random line from a file using a Python subroutine. Let's make a script work plan:

  1. Run subroutine
  2. Transfer the result of the subroutine to the clipboard
  3. Display popup message

Let's define the names of the directory and application files:

  • rndstr folder in home directory
    • source - the file from which we will take lines
    • rndstr.py - a subroutine that displays a random line from the source file to the console
    • rndstr.sh - script file

Create an application directory and move to it and create files there.

The first two points of the script plan can be combined by a pipeline, as a result, using Termux: API we get:

#!/bin/bash

python ~/rndstr/rndstr.py | termux-clipboard-set # 1 и 2 пункты плана работы

termux-toast "OK" # 3 пункт. Выводим всплывающее сообщение "ОК"

In the source file, you can put any text logically divided into lines, I decided to put aphorisms:

Source file listing

Искренность не есть истина. Л. Лавель
Терпи и воздерживайся. Эпиктет
Благородно только то, что бескорыстно. Ж. Лабрюйер
Будь благоразумно отважным. Б. Грасиан
Доброта лучше красоты. Г. Гейне
Для великих дел необходимо неутомимое постоянство. Ф.Вольтер
Если ты хочешь, чтобы тебе всегда угождали, прислуживай себе сам. Б. Франклин
Чрезмерная скромность есть не что иное, как скрытая гордость. А. Шенье
Очень умным людям начинают не доверять, если видят их смущение. Ф. Ницше
Бедность указывает на отсутствие средств, а не на отсутствие благородства. Д. Боккаччо
Нужно остерегаться доведения скромности до степени унижения. А. Бакиханов
Кто отказывается от многого, может многое себе позволить. Ж. Шардон
Когда нам платят за благородный поступок, его у нас отнимают. Н. Шамфор
Не получить вовсе - не страшно, но лишиться полученного обидно. Клавдий Элиан
Легче переносить терпеливо то, что нам не дано исправить. Гораций
Устаешь ждать, но насколько хуже было бы, если бы ждать стало нечего. Б. Шоу
Все приходит вовремя, если люди умеют ждать. Ф. Рабле
Своим терпением мы можем достичь большего, чем силой. Э. Берк
Надо уметь переносить то, чего нельзя избежать. М. Монтень
Кто в деле смел, тот слов не устрашится. Софокл
Я не люблю сражаться, я люблю побеждать. Б. Шоу
Затравленный и прижатый к стене кот превращается в тигра. М. Сервантес
Достойный человек не идет по следам других людей. Конфуций
Великий ум проявит свою силу не только в умении мыслить, но и в умении жить. Р. Эмерсон
Слава - товар невыгодный. Стоит дорого, сохраняется плохо. О. Бальзак
Сдержанность и уместность в разговорах стоят больше красноречия. Ф. Бэкон
Кто молчать не умеет, тот и говорить, не способен. Сенека Младший
Хорошие манеры состоят из маленьких жертв. Ф. Честерфилд
Добрый человек не тот, кто умеет делать добро, а тот, кто не умеет делать зла. В. Ключевский
Не произносите бесповоротных суждений! Августин
Ничего слишком! Солон

We just need to create a subroutine that extracts a random string from the source file.
Let's write the algorithm of the subroutine:

  1. Open source file
  2. Counting the number of lines in an open file
  3. Close the file (there is nothing to keep it open for extra time)
  4. We generate a random integer within the number of lines of the source file
  5. Open source file
  6. We output a line under the number of the generated number
  7. Closing the file

We implement the algorithm in Python (I write under Python 3.7):

import random  #  импортируем для генерации случайных чисел
import os  #  для получения пути

path = os.path.abspath(__file__)  #  получаем прямой путь до файла rndstr.py
path = os.path.dirname(path)  #  преобразуем в путь до директории
path = path  + '/source'  #  преобразуем в путь до файла source

f = open(path)  #  открываем файл
i = 0  #  обнуляем счетчик
for str in f: i+=1  #  считаем строки файла
f.close  #  закрываем файл

j = int(round(i * random.random()))  #  генерируем целое случайное число от 0 до i

f = open(path)  #  открываем файл
i = 0  #  обнуляем счетчик
for str in f:  #  перебираем строки из файла
    if i == j:  #  если счетчик строк равен сгенерированному числу
        print (str, end='')  #  выводим строку без перехода на новую
        break  #  выходим из цикла
    i+=1  #  увеличиваем счетчик на 1
f.close  #  закрываем файл

After the files are created and written, you need to give the file execution permissions rndstr.sh, and create an alias for quick launch.

alias rnst="~/rndstr/rndstr.sh"

Now typing in terminal rnst we will get a random aphorism on the clipboard, which, for example, can be used in correspondence.

Here we have written at least something useful. Relatively useful.

Ps

In the last step, I intentionally did not provide screenshots and did not analyze in detail some of the actions, writing only the contents of the files so that readers have the opportunity to work on their own.

On this "Termux step by step", I think it's worth finishing. Of course, these are only the very first steps, but now you can move forward yourself.

Initially, I planned to show in this cycle how to use nmap, sqlmap, but without me there are already a lot of articles on this topic. If you want me to continue the “Termux step by step” cycle, then there is a survey below and in the comments you can suggest what else to write about.

Only registered users can participate in the survey. Sign in, you are welcome.

Continue "Termux step by step"?

  • Yes

  • No

2 users voted. There are no abstentions.

Source: habr.com

Add a comment