Why does SSH hang at the end of these commands and how can I make it exit?

Solution 1:

Typically, SSH terminal sessions hang if there are still background connections still open. By background connections, I mean things such as:

  • X11 window forwarding
  • STDOUT and STDERR

Have a look at the connections that are still active on your hung SSH session by typing ~# in your hung SSH terminal.

It could be that your script is opening sessions that you didn't realize. Or your remote machine's terminal configs like .profile (or .bashrc, etc.) may have something in it that establishes a session. Good luck hunting!

By the way, some of the other escape sequences offered by OpenSSH clients may also be useful:

Supported escape sequences:
  ~.  - terminate connection (and any multiplexed sessions)
  ~B  - send a BREAK to the remote system
  ~C  - open a command line
  ~R  - Request rekey (SSH protocol 2 only)
  ~^Z - suspend ssh
  ~#  - list forwarded connections
  ~&  - background ssh (when waiting for connections to terminate)
  ~?  - this message
  ~~  - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)

One other thing, if you want your SSH to just run your commands and immediately exit -- that is, you don't want a remote terminal session -- you can use the -f option to ssh. That will force the SSH connection to be a background job.