Spawn subshell for SSH and continue with program flow

前端 未结 7 1025
别那么骄傲
别那么骄傲 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:31

    Maybe screen + ssh would fit the bill as well?

    Something like:

    screen -d -m -S sessionName cmd
    
    screen -d -m -S sessionName cmd &
    
    # reconnect with
    screen -r sessionName
    
    0 讨论(0)
  • 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' </dev/null &
    

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

    0 讨论(0)
  • 2020-12-19 16:37

    Having a ssh with pseudy tty on background shell

    In addition to @shellter's answer, I would like make some precision:

    where @shelter said:

    The man page on our system gave no hint that such a thing was possible

    On my system (Debian 7 GNU/Linux), if I hit:

    man -Pcol\ -b ssh| grep -A3 '^ *-t '
    

    I could read:

         -t      Force pseudo-tty allocation.  This can be used to execute arbi‐
                 trary screen-based programs on a remote machine, which can be
                 very useful, e.g. when implementing menu services.  Multiple -t
                 options force tty allocation, even if ssh has no local tty.
    

    Yes: Multiple -t options force tty allocation, even if ssh has no local tty.

    This mean: If you remotely run a tool that require access to pseudo terminal ( pty like /dev/pts/0), you could run them by using -t switch.

    But this would work only if ssh is run from a shell console (aka having his own pty). If you plan to run them is shell session without console, like background scripts, you may use Multiple -t to enforce pseudo tty allocation from ssh.

    Multiple ssh shell on one ssh connection

    In addition to answers from @tommy and @geekosaur, I would make some precision:

    @tommy point to a very intersting feature of ssh. Not sure this have a lot to do with answer, but speaking around long time connection, this feature has to be clearly understood.

    Once a connection is established, ssh could (and know how to) use them to drive a lot of thing in this one connection:

    • -L let you drive remote TCP connections to local machines/network. (full syntax is: -L localip:localport:distip:distport) where localip could be specified to permit other hosts from same local domain to access same tcp bind, and distip could by any host from distant network ( not only localhost ) sample: -L192.168.1.31:8443:google.com:443 permit any host from local domain to reach google through your host: http://192.168.1.31:8443

    • -R Same remarks in reverse way!

    • -M Tell ssh to open a local unix socket for bindind next ssh consoles. Simply open two terminal window. First in both window, hit: ssh somewhere than hit netstat -tan | grep :22 or netstat -tan | grep 192.168.1.31:22 (assuming 192.168.1.31 is your onw host's ip)

      Than compare close all your ssh session and in first terminal, hit: ssh -M somewhere and in second, simply ssh somewhere. you may see in second terminal:

      $ ssh somewhere
      + ssh somewhere
      Last login: Mon Feb  3 08:58:01 2014 from elsewhere
      

      If now you hit netstat -tan | grep 192.168.1.31:22 (on any of two oppened ssh session;) you must see that there is only one tcp connection.

      This kind of features could be used in combination with -L and maybe some sleep 86399...

      To work around a tcp killer router that close every inactive TCP connection from more than 120 seconds, I run:

      ssh -M somewhere 'while :;do uptime;sleep 60;done'
      

      This ensure connection stay up even if I dont hit a key for more than two minutes.

    0 讨论(0)
  • 2020-12-19 16:37

    Here's a few thoughts that might help.

    Sub-shells

    Sub-shells fork new processes, but don't return control to the calling shell. If you want to fork a sub-shell to do the work for you, then you'll need to append a & to the line.

    (ssh username@domain) &

    But this doesn't look like a compelling reason to use a sub-shell. If you had a number commands you wanted to execute in order from each other, yet in parallel from the calling shell, then maybe it would be worth it. For example...

    (dothis.sh; thenthis.sh; andthislastthingtoo.sh) &

    Forking

    I'm not sure why & isn't working for you, but it may be worth looking into nohup as well. This makes the command "immune" to hang up signals.

    nohup ssh username@domain (try with and without the & at the end)

    Passwords

    Not storing passwords in the script is essential for any ssh automation. You can accomplish that using public key cryptography which is an inherent feature of ssh. I wont go into the details here because there are a number of great resources all across the interwebs on setting this up. I strongly suggest investigating this further.

    • HOWTO: set up ssh keys - Paul Keck, 2001
    • SSH Keys - archlinux.org
    • SSH with authentication key instead of password - Debian Administration
    • Secure Shell - Wikipedia, the free encyclopedia

    If you do go this route, I also suggest running ssh in "batch mode" which will disable password querying and will automatically disconnect from the server if it becomes unresponsive after 5 minutes.

    ssh -o 'BatchMode=yes' username@domain

    Persistence

    Then if you want to persist the connection, run some silly loop in bash! :)

    ssh -o 'BatchMode=yes' username@domain "while (( 1 == 1 )); do sleep 60; done"

    0 讨论(0)
  • 2020-12-19 16:41

    You may want to try to double background myProg2 to detach it from the tty:

    # cf. "Wizard Boot Camp, Part Six: Daemons & Subshells",
    # http://www.linux-mag.com/id/5981
    (myProg2 &) &
    

    Another option may be to use the daemon tool from the libslack package:

    http://ingvar.blog.linpro.no/2009/05/18/todays-sysadmin-tip-using-libslack-daemon-to-daemonize-a-script/

    0 讨论(0)
  • 2020-12-19 16:45

    I had a script that looped on 6 servers, calling via ssh in the background. In 1 part of the script, there was a mis-behaving vendor application; the application didn't 'let go' of the connection properly. (other parts of the script using ssh in background worked fine).

    I found that using ssh -t -t cured the problem. Maybe this can help you too. (a teammate found this on the web, and we had spent so much time, I never went back to read the article that suggested this. The man page on our system gave no hint that such a thing was possible)

    Hope this helps.

    0 讨论(0)
提交回复
热议问题