Spawn subshell for SSH and continue with program flow

前端 未结 7 1024
别那么骄傲
别那么骄傲 2020-12-19 16:28

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

7条回答
  •  醉梦人生
    2020-12-19 16:33

    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 killed 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)

提交回复
热议问题