Spawn subshell for SSH and continue with program flow

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

提交回复
热议问题