Android and Linux

Saturday, January 7, 2012

ssh on ICS

Since getting the Galaxy Nexus, I've been unable to use ssh until now. The problem was something with the router. Everything was set up properly, all my other computers can ssh to each other, and I could ssh from outside my network, but once connected to wifi, I couldn't ssh from the computer to the phone or from the phone to the computer. I finally solved it by buying a new router.

There is still one oddity though. When connected to wifi, the phone will not ssh to the external IP address of anything on the network. What I mean is that if my computer's assigned IP address is 192.168.1.5 and ssh is running on port 1234 and the external IP address is 123.45.54.321, I should be able to connect to 123.45.54.321 port 1234. I always use that since it's the same address I would use if I were trying to connect remotely. But for some reason it won't work.

Luckily Tasker provides an easy fix. I set up a profile to write "connected" to /sdcard/Tasker/wifi when connected to my wifi and write "disco" when disconnected. Since I already had to write a script to connect to multiple ssh servers, I can read that file and see if I'm on wifi and use the proper IP.

#! /system/bin/sh

if grep -q connected /sdcard/Tasker/wifi
then
comp1ip=192.168.1.9
comp2ip=192.168.1.5
else
comp1ip=$(hip)
comp2ip=$(hip)
fi

case "$1" in

comp1)
echo "$comp1ip ssh-rsa AAA==" > /data/data/com.magicandroidapps.bettertermpro/home/.ssh/known_hosts

ssh USER@$comp1ip -i PATH/TO/KEYFILE -p PORT;;

comp2)
echo "$comp2ip ssh-rsa BBB==" > /data/data/com.magicandroidapps.bettertermpro/home/.ssh/known_hosts

ssh USER@$(hip) -i PATH/TO/KEYFILE -p PORT;;

esac


There's also another improvement that can be made to that script by changing the section for each computer.

comp1)
echo "$comp1ip ssh-rsa AAA==" > /data/data/com.magicandroidapps.bettertermpro/home/.ssh/known_hosts

if [ -z "$2" ]
then
ssh USER@$(hip) -i PATH/TO/KEYFILE -p PORT
else
shift; ssh USER@$(hip) -i PATH/TO/KEYFILE -p PORT "$*"
fi
;;


What this does is check for arguments to the script. If there are none, it will connect normally. If there are arguments, it will run them as commands on the remote computer.

So, the command s comp1 would login to computer 1, but s comp1 cd ~foo && touch bar will run the command on computer 1 to cd to the foo directory and create the file bar.

That makes it a lot simpler to bounce commands off the remote computer.

Followers