Termux шаг за шагом (часть 2)
Содержание:
Шаг 5
Установим Python и nano
Для установки Python’а пишем в терминале:
Теперь у нас установлен 2 и 3 Python.
За время работы над статьей, я открыл для себя еще один текстовый редактор nano, который приглянулся мне больше чем vim, давайте его установим:
Пользоваться им проще чем vim’ом, и nano имеет более дружественный интерфейс. На Android устройстве все же удобнее vim.
HelloWorld на Python в Termux
По большому счету можно было обойтись и без этого пункта, но поставить Python в Termux и не написать HelloWorld, на мой взгляд, моветон.
Я не ставлю своей целью учить кого-либо Python’у, так что не знающие могут просто скопировать код (или начать изучать самостоятельно, благо литературы хватает), а знающие могут и сами что-нибудь наваять. А я «под шумок» еще покажу способ вводить текст в терминале без редактора.
Если в процессе ввода вы не заметили ошибку и уже нажали Enter, то перейти на строку выше не получится, для этого закончите ввод нажав Ctrl + D (можно вообще прервать Ctrl + Z) и повторите все с начала. Поскольку мы использовали ‘>’ то файл будет переписан полностью. По этой причине не рекомендую использовать такой метод ввода, если вы не уверены что напишете код сразу без ошибок.
Can I use Termux for hacking?
Main Article: Hacking
Yes, you can, but this is more a question of your skills rather than Termux features.
We have some tools which may (or may not) help you in penetration testing. For example: aircrack-ng (set of utilities for Wi-Fi security audit), hydra (brute force tool), metasploit (platform for testing against known vulnerabilities) or nmap (port scanner). Various development tools like clang and python are available too.
Certain tools like aircrack-ng require your device to be rooted and/or even run a custom Linux kernel with additional drivers and patches.
A letter to hacking tutorial seekers: Beware of scripts suggested to be executed in various «hacking tutorials» available on the Internet. Most of them actually do not work properly (outdated ?). Some of them break Termux environment or even installs malware. Termux developers are not responsible about any damage which may happen by following these «tutorials».
Python module installation tips and tricks
It is assumed that you have or at least ,
and installed.
It also assumed that is not broken and works on your device.
Environment variable is not tampered or unset. Otherwise you
will need to patch modules’ source code to fix all shebangs!
| Package | Description | Dependencies | Special Instructions |
|---|---|---|---|
| electrum | |||
| gmpy2 | libgmp libmpc libmpfr | ||
| lxml | libxml2 libxslt | ||
| Numpy |
The fundamental package for scientific computing with Python |
||
| matplotlib | freetype libpng | ||
| pandas | |||
| pynacl | libsodium | ||
| pillow | libjpeg-turbo libpng | ||
| pyzmq | libzmq |
Advanced installation instructions
Some Python modules may not be easy to install. Here are collected information on how to get
them available in your Termux.
Numpy and Scipy
Before Numpy/Scipy installation, you need to subscribe to APT repository:
curl -LO https://its-pointless.github.io/setup-pointless-repo.sh bash setup-pointless-repo.sh
Then you can install Numpy or Scipy like a regular Termux package:
pkg install numpy pkg install scipy
OpenCV
OpenCV needs to be built from source using CMake, install it and other dependencies
with:
pkg install build-essential cmake libjpeg-turbo libpng python
Numpy is also required, see instructions for installing it above.
The rest of the instructions can be copy-pasted straight away, but if you are not sure
if you have all dependencies then it might be best to do it in two steps: first all
commands up until the command and then in a second
step make and make install.
To get the sources, git clone (from a suitable folder):
git clone https://github.com/opencv/opencv cd opencv
You should now be in the opencv folder. Let’s create a build folder where we will
build the package:
mkdir build cd build
To configure the package for python3 but not python2 (change the on/off flags to
use python2 instead of python3) we run:
LDFLAGS=" -llog -lpython3" cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=$PREFIX -DBUILD_opencv_python3=on -DBUILD_opencv_python2=off -DWITH_QT=OFF -DWITH_GTK=OFF ..
Last command will throw errors if there are missing dependencies. After this we can
compile the package with
make
and then install the files with
make install
Tkinter
Tkinter is splitted of from the package and can be installed by
pkg install python-tkinter
We do not provide Tkinter for Python v2.7.x.
Since Tkinter is a graphical library, it will work only if X Windows System environment
is installed and running. How to do this, see page Graphical Environment.
Installing Python modules from source
Some modules may not be installable without patching. They should be installed from
source code. Here is a quick how-to about installing Python modules from source code.
1. Obtain the source code. You can clone a git repository of your package:
git clone https://your-package-repo-url cd ./your-package-repo
or download source bundle with :
pip download {module name}
unzip {module name}.zip
cd {module name}
2. Optionally, apply the desired changes to source code. There no universal guides on that,
perform this step on your own.
3. Optionally, fix the all shebangs. This is not needed if is installed
and works correctly.
find . -type f -not -path '*/\.*' -exec termux-fix-shebang "{}" \;
4. Finally install the package:
python setup.py install
Шаг 4
Погружаемся в кроличью нору Termux:API
API как много в этом слове для сердца кодера слилось
Для начала установим Termux:API из Google Play Market’а (после не помешает перезапустить Termux):
Далее нам нужно установить пакет API в консоли Termux’а:
Для экспериментов я использую Android 5.1.1, для владельцев Android 7 нужно «защитить» Termux: API, зайдя в ‘Настройки’ > ‘Защищенные приложения’, в противном случае вызовы API, такие как , будут зависать. (См. wiki проекта)
Теперь стоит поближе познакомится с приобретенными возможностями. Самое свежее и подробное описание Termux:API можно найти на wiki проекта. Я же постараюсь выбрать самое наглядное и интересное, что позволит набить руку для самостоятельной работы в дальнейшем.
Несколько примеров Termux:API
- termux-battery-status
Возвращает состояние батареи - termux-brightness
Устанавливает яркость экрана от 0 до 255 - termux-toast
Показывает временное всплывающее уведомление - termux-torch
Включает фонарик - termux-wifi-scaninfo
Возвращает информацию о последнем сканировании сетей Wi-Fi
Нетрудно заметить, что возвращаемые значения являются строками, словарями, списками словарей, в общем типами данных, с которыми прекрасно работает Python, поэтому следующим шагом мы его установим.
Dependencies
| Package | Description | Installation |
|---|---|---|
| x11-repo | Termux repo for x11 packages | |
| vnc server | For graphical output | |
| openbox wm | Openbox Window Manager | |
| xsetroot | Set color background for X | |
| xterm | X terminal | |
| xcompmgr | Composite manager or desktop effects | |
| xfsettingsd | The settings daemon, to set themes & icons | |
| polybar | Easy and fast status bar | |
| st | Suckless/Simple terminal | |
| geany | Graphical text editor | |
| thunar | File manager (optional) | |
| pcmanfm | File manager | |
| rofi | An application launcher | |
| feh | Simple image viewer | |
| neofetch | System info program | |
| git | VCS, for cloning repos | |
| wget | Command line downloader | |
| curl | To transfer/get internet data | |
| zsh | A very good shell | |
| vim | Command line text editor (! — hard to exit :D) | |
| htop | System monitor (optional) | |
| elinks | Command line web browser (optional) | |
| mutt | Command line mail client (optional) | |
| mc | Command line file manager (optional) | |
| ranger | Command line file manager (optional) | |
| cmus | Command line music player (optional) | |
| cava | Console-based audio visualizer (optional) | |
| pulseaudio | Sound system & audio server (optional) |
You can install all important programs simply pasting this in the termux —
Why do I keep getting a ‘/bin/sh bad interpreter’ error?
This error is thrown due to access script interpreter at nonexistent location.
Termux does not have common directories like /bin, /sbin, /usr/bin at their standard place. There is an exception for certain devices where /bin is a symbolic link to /system/bin, but that does not make a difference.
Interpreters should be accessed at this directory only:
/data/data/com.termux/files/usr/bin
There are three ways to fix this:
- Install termux-exec by using . It won’t affect the current session, but after a restart should work without any setup. Not needed if your Termux is up to date. If still not working, try the next workaround.
- Use command to fix the shebang line of specified file.
- Use from package proot to setup a chroot environment mimicking a normal Linux file system in Termux.
How do I fix a broken environment?
Main Article: Recover a broken environment
You can start a failsafe shell through application shortcut and try to repair from there. You will not have access to Termux utilities until these environment variables are set:
export PREFIX=/data/data/com.termux/files/usr
export PATH=${PATH}:${PREFIX}/bin
In cases where environment was broken due to package manager failure or deletion of some important files, the easiest way of recovery will be to delete whole $PREFIX, restart Termux application and install packages from scratch.
More information available in Recover a broken environment.
Шаг 7
Сделаем хоть что-то полезное
Относительно полезное
Сформулируем техзадание
Приложение должно после запуска помещать в буфер обмена случайную строку из файла и оповещать об этом всплывающим сообщением.
За основу возьмем bash-скрипт, случайную строку из файла будем извлекать при помощи подпрограммы на Python’е. Составим план работы скрипта:
- Запустить подпрограмму
- Передать результат работы подпрограммы в буфер обмена
- Вывести всплывающее сообщение
Определимся с названиями директории и файлов приложения:
- папка rndstr в домашней директории
- source — файл из которого будем брать строки
- rndstr.py — подпрограмма выводящая в консоль случайную строку из файла source
- rndstr.sh — файл скрипта
Создаем директорию приложения и переместившись в нее создаем там файлы.
Первые два пункта плана скрипта можно объединить конвейером, в итоге, используя Termux:API получаем:
В файл source вы можете поместить любой текст логически разделенный на строки, я решил поместить афоризмы:
Нам осталось создать подпрограмму извлекающую случайную строку из файла source.
Распишем алгоритм работы подпрограммы:
- Открываем файл source
- Считаем количество строк в открытом файле
- Закрываем файл (нечего его лишнее время открытым держать)
- Генерируем случайное целое число в пределах количества строк файла source
- Открываем файл source
- Выводим строку под номером сгенерированного числа
- Закрываем файл
Реализуем алгоритм на Python (я пишу под Python 3.7):
После того как файлы созданы и записаны, нужно дать права на исполнение файлу , и создать alias для быстрого запуска.
Теперь введя в терминале мы получим в буфер обмена случайный афоризм, который, например, можно использовать в переписке.
Вот мы и написали хоть что-то полезное. Относительно полезное.
P.S.
Я намеренно в последнем шаге не стал приводить скриншоты и не разобрал подробно некоторые действия, расписав только содержимое файлов, чтобы у читателей была возможность поработать самостоятельно.
Screenshots
Well, Here are some ideas or things you can do with termux and how you can make doing these stuff easy with a graphical desktop. And FYI, I’m not doing anything illegal or sponsoring any kind of Hacking and Cracking. Termux is a powerful tool, use it with responsibilities.
Rofi : Rofi app launcher.
Polybar Style : Rofi based script to change the colors of polybar.
Stuff : Running cmatrix, htop, pipes, etc.
Internet : Elinks as browser and mutt as mail client.
File Managers : Pcmanfm and thunar, graphical file managers.
CLI File Managers : Ranger & MC, console based file managers.
Text Editors : Runnig vim, nano (CLI based) & geany (graphical) text editors.
Showing Off : Ah, just some tools —


Resolution : on 1920×1080 display resolution

Additional Tools
You can install additional tools for termux, to make it visually look good.
- Oh my zsh, Setup zsh with oh-my-zsh framework.
- Termux style, Change color and fonts in termux.
Not Supported Yet
- Bitmap Fonts
- SVG Icon Packs
- .Xresources/.Xdefaults For xterm/aterm
- No Web Browser (Expected Midori)
- No Hardware Acceleration
- Some Other Things
FYI
- First thing first, the guide above may have some errors, everybody make mistakes.
- If you face any problem or get any error, you can create an issue & i’ll help.
- There are some scripts made by me and some are made by other people, I’ve just put those here collectively.
- You may need to edit some scripts accoring to your need (like, battery, network email for polybar & .muttrc, .gitconfig)
- I’ll make more desktop configs and try to configure different window managers (fluxbox, dwm) by time.
- Share this repository with your friends.
Using the SSH client
You can obtain an SSH client by installing either `openssh` or `dropbear`.
Usage example
To login to a remote machine where the ssh daemon is running at the standard port (22):
ssh user@hostname_or_ip
Same as above, but if the ssh daemon running on different port, e.g. 8022:
ssh -p 8022 user@hostname_or_ip
Using public key authentication with ssh running on the standard port and a private key stored in the file `id_rsa`:
ssh -i id_rsa user@hostname_or_ip
Note, that if `id_rsa` will be stored in `~/.ssh` directory, you can omit specifying it in the command. But if you have multiple keys, it is necessary to pick a specific key with `-i {path_to_privkey}`.
SSH Agent
Important note: this does not work for Dropbear.
If you wish to use an SSH agent to avoid entering passwords, the Termux openssh package provides a wrapper script named `ssha` (note the `a` at the end) for ssh, which:
- Starts the ssh agent if necessary (or connect to it if already running).
- Runs the `ssh-add` if necessary.
- Runs the `ssh` with the provided arguments.
This means that the agent will prompt for a key password at first run, but remember the authorization for subsequent runs.
Установка Metasploit Framework
В дистрибутивах, предназначенных для тестирования на проникновение (к примеру, Kali или Parrot OS), этот продукт либо предустановлен, либо легко устанавливается следующей командой:
Если же ты хочешь использовать Metasploit Framework, например, в Ubuntu, то его можно установить из официального репозитория. Для этого набери в консоли следующие директивы:
База данных Metasploit
Довольно часто пользователям Metasploit приходится ломать сети, содержащие очень много хостов. И наступает момент, когда аккумулирование всей полученной информации занимает непозволительно долгое время. Именно тогда начинаешь ценить возможность работы Metasploit Framework с СУБД PostgreSQL. Metasploit может сам сохранять и удобно формализовать полученную информацию благодаря модулю msfdb. Для работы с базами необходимо запустить службу и создать базу для Metasploit.
Сообщение msfdb об успешном создании базы данных
Проверить подключение к базе данных можно из самого фреймворка, выполнив команду .
Успешное подключение к базе данных Metasploit
Чтобы было удобней работать с различными областями (хостами, сетями или доменами) и разделять данные для структуризации, msfdb имеет поддержку так называемого рабочего пространства. Давай добавим новое пространство в наш проект.
Создание нового рабочего пространства
Теперь мы действуем в созданном рабочем пространстве. Представим, что мы находимся в сети 192.168.6.0.24. Давай поищем в ней доступные хосты. Для этого будем использовать , но из Metasploit и с привязкой к текущей базе данных — .
Сам вывод Nmap нам неинтересен: все, что нужно, будет сохранено в базе данных. К примеру, у нас есть уже все просканированные хосты и мы можем их просмотреть одним списком с помощью команды .
Список просканированных хостов, сохраненный в базе данных
Но заодно с хостами были сохранены и все службы, список которых у нас теперь также всегда будет под рукой. При этом мы можем посмотреть как вообще все службы на портах, так и список служб для определенного хоста.
Список всех найденных службСписок найденных на определенном хосте служб
У базы данных msfdb есть очень крутая возможность — сохранение всех найденных учетных данных. Об этой функции я расскажу позже, а сначала несколько слов о возможностях брутфорса, которыми располагает фреймворк. Полный список перебираемой информации для коллекционирования учетных данных можно получить следующей командой:
Модули для брутфорса учетных данных некоторых служб
Обрати внимание на SMB. Чтобы узнать, для чего именно предназначен определенный модуль и его описание (со ссылкой на cvedetails), а также посмотреть данные, которые нужно передать в качестве параметров, следует воспользоваться командой
Описание модуля smb_login
Давай выберем этот модуль, зададим название домена, имя пользователя, интересующий нас хост и список паролей.
Настройка модуля smb_loginОбнаруженный smb_login пароль для целевого пользователя
Если найденный пользователь — администратор, Metasploit сообщит нам об этом, что очень удобно. Но ведь в нашей сети может быть 100 машин и даже больше, а на них наверняка запущено множество служб. Как правило, удается собрать много учетных данных, используя только модули брутфорса. Использование msfdb позволяет не тратить время на коллекционирование всех обнаруженных логинов, хешей, паролей, так как они автоматически остаются в хранилище учетных данных, посмотреть которое можно командой .
Продолжение доступно только участникам
Материалы из последних выпусков становятся доступны по отдельности только через два месяца после публикации. Чтобы продолжить чтение, необходимо стать участником сообщества «Xakep.ru».
Присоединяйся к сообществу «Xakep.ru»!
Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», увеличит личную накопительную скидку и позволит накапливать профессиональный рейтинг Xakep Score!
Подробнее
Я уже участник «Xakep.ru»
Why does a compiled program show warnings about DT_FLAGS_1=0x8?
This warning is completely safe and just notifies developer that linker detected unused extra information inside executable file. In case of DT_FLAGS_1=0x8, it warns about RTLD_NODELETE ELF section. Besides DT_FLAGS_1=0x8, there more types of ELF sections which are not handled by Android linker.
To make this warning disappear you need to use utility «termux-elf-cleaner» binary file and probably on all its dependencies.
pkg install termux-elf-cleaner termux-elf-cleaner ./myprogram ./libmysharedlibrary.so
Number of supported ELF sections increases with Android OS version. On Android 7.0 and higher you are unlikely to get linker warnings.
Шаг 2
Облегчи себе жизнь
Чтобы не мучить себя без нужды вводом команд с экранной клавиатуры (в «полевых» условиях, конечно, от этого не уйти) есть два пути:
- Подключить к Android устройству полноценную клавиатуру любым удобным способом.
- Воспользоваться ssh. Проще говоря, у вас на компьютере будет открыта консоль Termux’а запущенного на вашем Android устройстве.
Я пошел по второму пути, хотя он и немного сложен в настройке, но все окупится удобством использования.
На компьютере необходимо установить программу ssh клиент, я пользуюсь Bitvise SSH Client, и все дальнейшие действия совершаются в этой программе.
Поскольку мы будем подключаться по методу Publickey с использованием файла-ключа, необходимо этот файл создать. Для этого в программе Bitvise SSH Client на вкладке Login щелкаем по Client key manager в открывшемся окне генерируем новый публичный ключ и экспортируем его в OpenSSH формате в файл с названием termux.pub (на самом деле можно любое название). Созданный файл помещаем во внутреннюю память вашего Android устройства в папку Downloads (к этой папке, и еще к нескольким, Termux имеет упрощенный доступ без root).
Во вкладке Login в поле Host вводим IP вашего Android устройства (узнать можно введя в Termux команду ifconfig) в поле Port должно быть 8022.
Теперь переходим к установке OpenSSH в Termux, для этого вводим следующие команды:
Возвращаемся к Bitvise SSH Client и нажимаем кнопку Log in. В процессе подключения появится окно, в котором выбираем Method – publickey, Client key это Passphrase (если вы ее указали при генерации файла-ключа).
В случае успешного подключения (если все сделали, как написано, то должно подключиться без проблем) откроется окно.
Теперь мы можем вводить команды с ПК а выполняться они будут на вашем Android устройстве. Не сложно догадаться какие это дает преимущества.
Шаг 3
Настроим Termux, установим дополнительные утилиты
Прежде всего давайте установим bash-completion (сокращалку, волшебный-Tab, кто как называет). Суть утилиты в том что, вводя команды вы можете нажав Tab воспользоваться автозаполнением. Для установки пишем:
Ну что за жизнь без текстового редактора с подсветкой кода (если вдруг захочется покодить, а оно захочется). Для установки пишем:
Пользоваться vim`ом не сложно, чтобы открыть файл 1.txt (если его нет, то он создастся) пишем:
Раз мы теперь можем создавать и редактировать файлы, давайте немного улучшим вид и информативность командной строки Termux’а. Для этого нам нужно присвоить переменной окружения PS1 значение «:\w$ » (если интересно что это и с чем его едят, прошу сюда). Чтобы это сделать нам нужно в файл ‘.bashrc’ (лежит в корне и выполняется при каждом запуске оболочки) добавить строку:
Для простоты и наглядности воспользуемся vim`ом:
Вписываем строку, сохраняем и выходим.
Добавить строку в файл можно и другим способом, воспользовавшись командой ‘echo’:
В файл .bashrc так же можно вписать alias’ы – сокращения. Например мы хотим одной командой проводить update и upgrade сразу. Для этого в .bashrc добавляем строку:
Для внесения строки можно воспользоваться vim’ом или командой echo (если не получается самостоятельно – см. ниже)
Синтаксис alias’ов таков:
Итак, добавляем сокращение:
Вот еще несколько полезных утилит
Ставить через apt install
man — Встроенная справка для большинства комманд.
man %commandname
imagemagick — Утилита для работы с изображениями(конвертирование, сжатие, обрезка). Поддерживает много форматов включая pdf.Пример: Сконвертировать все картинки из текущей папки в один pdf и уменьшить их размер.
convert *.jpg -scale 50% img.pdf
ffmpeg — Один из лучших конвертеров аудио/видео. Инструкцию по использованию гуглите.
mc — Двухпанельный файловый менеджер наподобие Far.
Впереди еще немало шагов, главное что движение начато!
Using the SFTP
Package OpenSSH provides a tool for accessing remote hosts over SFTP. This will allow you to work with files in same way as via FTP but with better security.
Connecting to Termux (sshd listening on port 8022):
$ sftp -P 8022 192.168.1.20
Connecting to somewhere else (sshd listening on standard port):
$ sftp sftp.example.com
However, to use command line SFTP client you should know some basic commands:
- cd PATH — change current directory to `PATH`.
- get REMOTE — download file `REMOTE` and rename it as `LOCAL` (optional).
- mkdir PATH — create directory `PATH`.
- ls — list files in directory `PATH`. If no argument, files in current directory will be listed.
- put LOCAL — Upload file `LOCAL` and rename it as `REMOTE` (optional).
- rm FILE — Delete file `FILE`.
This is not a complete list of SFTP commands. To view all available commands, consider to view man page () or view short help in interactive SFTP session by issuing command `help`.
MOSH
Mosh is a remote terminal application that allows roaming, supports intermittent connectivity, and provides intelligent local echo and line editing of user keystrokes.
Usage example
Important note: Mosh should be installed on both client and server side.
Connecting to remote host (sshd listening on standard port):
mosh user@ssh.example.com
Connecting to Termux (sshd listening on port 8022):
mosh --ssh="ssh -p 8022" 192.168.1.25
Rsync
Rsync is a tool for synchronizing files with remote hosts or local directories (or drives). For better experience of using rsync, make sure that package `openssh` (or `dropbear`) is installed.
Usage example
Sync your photos with PC:
$ rsync -av /sdcard/DCIM/ user@192.168.1.20:~/Pictures/Android/
Get photos from remote Android device:
$ rsync -av -e 'ssh -p 8022' 192.168.1.3:/sdcard/DCIM/ /sdcard/DCIM/
Sync local directories (e.g. from external sdcard to Termux home):
$ rsync -av /storage/0123-4567/myfiles ~/files
You may want to see man page (`man rsync`) to learn more about it’s usage.
Termux App for PC
Termux is a powerful app that emulates Linux OS on PCs and enables the use of Linux command lines. Following the automatic installation of the app, you get a minimal base system that is upgradable via the APT package. The app works directly and requires no rooting on devices.

Termux is a secure app in that it gets access to remote servers via the SSH client. The Termux app is highly customizable and allows any installation via the Debian-Ubuntu GNU/Linux APT package management system. With the excellent terminal emulation and a vast collection of Linux packages, it’s simply amazing what you can get.
Features of Termux App
- Access servers over SSH
- Bash & ZSH shells available
- Files editable with nano & vim.
- Compile code with Clang & GCC
- Python console as a calculator
- GIT & SVN to check out projects
- Frotz to run text-based games
- Supports keyboard shortcuts and has full mouse support.
Download Termux APK Free
| Name | Termux |
| App Version |
Varies with device |
| Category | Tools |
| App Size |
Varies with device |
| Supported Android Version |
Varies with device |
| Last Update | June 2020 |
| License Type | Free |
| Download File | Termux APK |
How to Install Termux for PC (Windows and Mac)
There are 2 methods to install Termux on your PC Windows 7, 8, 10 or Mac.
Method 1: Install Termux on PC using LDPlayer
First of all, You need to Download LDPlayer on your PC (Windows/Mac) from the given link below.
- Double click on the file you downloaded to install LDPlayer Android Emulator on your PC (Windows/Mac).
- It will launch a setup wizard. Just follow on-screen instruction and installation will be done in a few minutes.
- Once it is installed. Click on the LDPlayer icon on your desktop to launch the Emulator.
- Open Google Play Store and Type “Termux” in the search bar.
- Find the Termux app from appeared search results and Click on Install.
- It will take a few seconds to install Termux on your PC (Windows/Mac).
- After successfully installed click on Termux from the LDPlayer home screen to start using it.
Method 2: Install Termux on PC using BlueStacks
First of all, You need to Download BlueStacks on your PC (Windows/Mac) from the given link below.
- Install BlueStacks Android Emulator on your PC (Windows/Mac).
- Open BlueStacks Android Emulator.
- Open Google Play Store and Type “Termux” in the search bar.
- Find the Termux app from appeared search results and Click on Install.
- After installed click on Termux from the home screen to start using it.
Termux Alternatives
ConnectBot
This is an open-source Secure Shell (SSH) client that simultaneously manage SSH sessions, create secure tunnels, etc. The servers typically run on UNIX-based servers with the ultimate goal of using shells on remote machines and transfer files. Its SSH2 standard encryption serves to make command and data secure.
Linux Deploy
This app is a reversible android emulator that enables the use of Linux OS on Android devices. With this app, users can operate many Linux files, including Ubuntu, Fedora, etc.
Script Manager
This free Android app doubles as a multi-support emulator and a script editor. Its vast functionality allows users to run scripts at boot-up, add codes, and organize cron jobs. The app could also serve as a root explorer, multi-tab browser, and file manager.
Termux is an excellent terminal emulator for Android devices that enables the use of shells, access to servers, and editing of files. This app is a total all-round package with features for both productivity and entertainment.
Шаг 6
Bash-скрипты
Bash-скрипты это замечательный способ автоматизации работы с терминалом. Скрипт представляет из себя файл с расширением .sh (расширение не обязательно) содержащий набор команд терминала часть из которых мы уже изучили
Вот список большинства команд, все должно работать, но обратите внимание, что это список для «взрослого» Linux’а, а не для Termux’а, а вот просто шикарный материал по bash-скриптам
При помощи скриптов можно автоматизировать практически все монотонные действия. Напишем простейший bash-скрипт выводящий значение из созданной им же переменной, я снова воспользуюсь cat’ом, вы же можете использовать нормальный текстовый редактор, а особо желающие себя потренировать могут использовать echo.
Bash-скрипт с Termux:API
Давайте напишем уже что-нибудь отличающееся от пресловутых HelloWorld’ов, но столь же бесполезное. Наш скрипт будет:
- выполнять запрос API termux-battery-status
- сохранять полученные данные в файл test.txt
- выводить данные из файла на экран
- выполнять написанную ранее программу hello-world.py
- полученные от программы данные записывать в файл test.txt
- выводить данные из файла на экран
- переносить данные из файла в буфер обмена
- выводить на экран содержимое буфера обмена
- выводить всплывающее сообщение с данными из буфера обмена
Сначала создадим папку для работы и скопируем туда hello-world.py как test.py, создадим в этой папке файлы test.sh и test.txt:
Теперь любым удобным способом в файл test.sh запишем скрипт:
Теперь находясь в папке bashscript пишем наблюдаем в терминале на Android устройстве:
Вот мы и написали запланированный bash-скрипт. Можно разбавить его выводом в консоль информации по выполнению каждого действия (при помощи echo), это оставлю для читателей.
Configuration
Now all the necessary programs are installed, it’s time to configure the system.
So, first clone this repo by,
Now go to the cloned directory termux-desktop and copy or move home & usr (Basically ) directory to /data/data/com.termux/files. you can do it by,
or
Warning : I’m assuming you’re doing this on a fresh termux install. If not so, please backup your files before running these command above. These commands will forcefully copy or move files in home & usr directory. So, before doing that, take a look inside the repo directories, and backup your existing config files (like .vimrc, .zshrc, .gitconfig, etc).
VNC Server
Now, Let’s configure the vnc server for graphical output. Run —
At first time, you will be prompted for setting up passwords —
Note that passwords are not visible when you are typing them and maximal password length is 8 characters.
If everything is okay, you will see this message —
It means that X (vnc) server is available on display ‘localhost:1’.
Finally, to make programs do graphical output to the display ‘localhost:1’, set environment variable like shown here (yes, without specifying ‘localhost’):
You may even put this variable to your bashrc or profile so you don’t have to always set it manually unless display address will be changed.
Now You can start the vnc server by,
And to stop the server, run —
Determine port number on which VNC server listens. It can be calculated like this: 5900 + {display number}. So for display ‘localhost:1’ the port will be 5901.
Now open the VNC Viewer application and create a new connection with the following information (assuming that VNC port is 5901) —
Now launch it. You will be prompted for password that you entered on first launch of ‘vncserver’. And because you’ve copy pasted everthing, you’ll be headed to this desktop —

Well, That’s it. You’ve successfully installed a beautiful graphical desktop on termux. Hurray!!!