in my bash loop over a list of some servers, if the ssh connects the bash script exits

前端 未结 2 1073
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 10:44

I have a quick script to run a command on each server using ssh (i am sure there are lots of better ways to do this, but it was intended to just work quick!!). For the test1

相关标签:
2条回答
  • 2020-12-11 11:07

    You should pass the -n flag to ssh, to prevent it messing with stdin:

    ssh -n -q -oPasswordAuthentication=no -i id_dsa user1@${line} date
    

    I tested this with my own server and reproduced the problem, adding -n solves it. As the ssh man page says:

    Redirects stdin from /dev/null (actually, prevents reading from stdin)

    In your example, ssh must have read from stdin, which messes up your read in the loop.

    0 讨论(0)
  • 2020-12-11 11:18

    I think the reason is that as ssh is being forked and exec'd in your bash script the script's standard input is being reopened so your read simultaneously terminates. Try re-crafting as follows:

    for line in test1 test2 server1 server2
    do
        if [ "${line:0:1}" != "#"  ]; then
            ssh -q -oPasswordAuthentication=no -i id_dsa user1@${line} date
        fi
    done
    

    or maybe run the ssh in a sub-shell like this:

    ( ssh -q -oPasswordAuthentication=no -i id_dsa user1@${line} date )
    
    0 讨论(0)
提交回复
热议问题