0

I have a script when I use multiple ssh connections inside HEREDOC, like so:

ssh -A -tt -l user 192.168.1.2 <<EOF
  ping server1 -c3
  ssh server2
  nslookup www.gogole.com
  exit
  ssh server3
  ifconfig
  exit
EOF

however, when I use exit inside EOF, it stops processing script instead of exiting SSH session, any idea/trick how I can exit ssh session instead of the whole script ?

#'~.'  - terminate session - doesn't work unfortunately
  • shouldn't you be nesting here script ? do you intend to run nslookup www.google.com on server2 ? – Archemar Sep 14 '17 at 10:57
  • yes, I want to run nslookup www.google.com on server2 – mauek unak Sep 14 '17 at 10:58
2

If you want to stick to here doc

ssh -A -tt -l user 192.168.1.2 <<EOF
  ping server1 -c3
  ssh server2 <<foobar1
  nslookup www.gogole.com
  more commands
  exit
foobar1
  ssh server3 <<foobar2
  ifconfig
  more more commands
  exit
foobar2
EOF
  • you can use any word to close here doc.
  • deleimiter must start a line.
  • or use <<-word
| improve this answer | |
  • Neither exit should be necessary. – Kusalananda Sep 14 '17 at 11:24
  • actually, if I omit exit, script connects to ssh, run commands, and stops, for some reason. while when I use exit, script disconnects from ssh server and continues .. – mauek unak Sep 14 '17 at 11:44
  • this approach is readable and working, thanks. maybe one more thing, I had to add another 'exit' before closing EOF, to exit initial ssh connection – mauek unak Sep 14 '17 at 11:47
  • I think -tt option is responsible for those exit. – Archemar Sep 14 '17 at 12:06
1
ssh -A -tt -l user 192.168.1.2 <<EOF
  ping server1 -c3
  ssh server2 nslookup www.gogole.com
  ssh server3 ifconfig
EOF

The ssh command will exit when it has finished executing the given commands.

For multiple commands, use sh -c:

ssh -A -tt -l user 192.168.1.2 <<EOF
  ping server1 -c3
  ssh server2 sh -c 'nslookup www.gogole.com; echo done'
  ssh server3 sh -c 'ifconfig; df -k'
EOF

If you have more than a few basic things to do on server2 and server3, create scripts on those servers and run these instead.

| improve this answer | |
  • well yes, this will work, only that i need to run multiple commands on server2 and server3, I didn't state that in my question, my bad – mauek unak Sep 14 '17 at 11:10
  • @mauekunak See update. – Kusalananda Sep 14 '17 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.