SSH session never closes when executing "apt-get install"

Solution 1:

The following answer on SF did the trick:

ssh fails to execute remote command when run from cron bash script

The -t flag forces a pseudo-tty allocation, except perhaps when there is no TTY locally. But passing the flag twice like in -t -t just pretends to do it. And that solved the problem.

See the SSH documentation:

-t Force pseudo-tty allocation. This can be used to execute arbitrary 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.

Now, why did that work? It turns out that debconf does not complain anymore about the frontend in the logs. So I believe that the double -t sets (lures?) debconf as needed, which allows apt-get install completion to end the SSH session cleanly.

Solution 2:

As I looked through it, this may do the job. Calling whatever command should be followed by exit and heredoc. Found the solution, but haven't tried it personally.

ssh user@myremotemachine <<-EOF
free -m
exit
EOF

Original answer comes from here: http://www.thetechrepo.com/main-articles/529-execute-a-command-remotely-over-ssh-and-then-close-the-connection

Solution 3:

Under debian/jessie I was successful with this command:

ssh user@host "TERM=READLINE sudo apt-get install --reinstall less && echo done"

But perhaps you should consider to use ansible for this and other upcomming tasks http://docs.ansible.com/ansible/apt_module.html