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 Openssh based sshd for login from a remote machine which is quite handy for console work and file-transfer (e.g. using sshfs).

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 that can be used to forward whatever port Termux uses to the regular port 22.

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

#!/data/data/com.termux/files/usr/bin/bash

trap ctrl_c INT

function ctrl_c() {
  pkill tcpsvd
  pkill sshd
  pkill tsu
}

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

# As root call iptables

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

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

# As root start the ftpd server
tcpsvd -u root -vE 0.0.0.0 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 }}