I\'m trying to write a shell script that automates certain startup tasks based on my location (home/campusA/campusB). I go to University and take classes in two different ca
The problem with &
is that ssh loses access to its standard input (the terminal), so when it goes to read something to send to the other side it either gets an error and exits, or is kill
ed by the system with SIGTTIN
which will implicitly suspend it. The -n
and -f
options are used to deal with this: -n
tells it not to use standard input, -f
tells it to set up any necessary tunnels etc., then close the terminal stream.
So the best way to do this is probably to do
ssh -L 9999:localhost:9999 -f host & # for some random unused port
and then manually kill the ssh
before logout. Alternately,
ssh -L 9999:localhost:9999 -n host 'while :; do sleep 86400; done'
(The redirection is to make sure the SIGTTIN
doesn't happen anyway.)
While you're at it, you may want to save the process ID and shut it down from your .logout
/.bash_logout
:
ssh -L 9999:localhost:9999 -n host 'while :; do sleep 86400; done' < /dev/null & echo $! >~.ssh_pid; chmod 0600 ~/.ssh_pid
and in .bash_logout
:
if test -f ~/.ssh_pid; then
set -- $(sed -n 's/^\([0-9][0-9]*\)$/\1/p' ~/.ssh_pid)
if [ $# = 1 ]; then
kill $1 >/dev/null 2>&1
fi
rm ~/.ssh_pid
fi
The extra code there attempts to avoid someone sabotaging your ~/.ssh_pid
, because I'm a professional paranoid.
(Code untested and may have typoes)