Android Termux's SSHD on port 22

Termux is a console Application which features most of the familiar GNU userland utilities.

There is even an sshd, for login from a remote machine, which is quite handy for console work and file-transfer (e.g. using scp).

Unfortunately ssh (running with the termux userid) will be unable to bind to port 22. I also like to have an FTP server answering on the regular port 21.

For a rooted phone Termux provides a package called tsu (like a sudo for Android) that can be used to forward whatever port Termux uses to the regular port 22.

So here is the script I use which will run sshd and ftpd and redirect port 22 to port 8022 and 8021 to 21.


trap ctrl_c INT

function ctrl_c() {
  pkill tcpsvd
  pkill sshd
  pkill tsu

if [ "$UID" != "0" ]; then
  tsu -a -e -c $0
  exit 0

# As root call iptables

if ! /system/bin/iptables -L PREROUTING -t nat -n |grep -q 8021
    echo "Redirecting port 8021 to 21"
    /system/bin/iptables -t nat -A PREROUTING -p tcp --dport 21 -j REDIRECT --to-port 8021

if ! /system/bin/iptables -L PREROUTING -t nat -n |grep -q 8022
    echo "Redirecting port 8022 to 22"
    /system/bin/iptables -t nat -A PREROUTING -p tcp --dport 22 -j REDIRECT --to-port 8022

# As root start the ftpd server
tcpsvd -u root -vE 8021 ftpd -w /

The script also features a CTRL+C trap, so when you CTRL+C to stop the script, it will stop both servers.

{{ message }}

{{ 'Comments are closed.' | trans }}