After sending shutdown command, ssh session doesn't terminate

This worked for me:

apt-get install libpam-systemd dbus

Also make sure that you have UsePAM yes in your ssh config.

grep -i UsePAM /etc/ssh/sshd_config

Unfortunately, you need to reboot for the solution to take effect...

Detailed explanations on serverfault.


Looks like that's a systemd issue currently tracked under bug #751636.

When the host is shut down or restarted, systemd might shut down the network before it kills the ssh session.

There are a couple of solutions provided but nothing concrete:

  1. Using acpid/acpi-support-base to handle the power events & add the following to the /etc/acpi/powerbtn-acpi-support.sh

    else
    -       # Normal handling.
    -       /sbin/shutdown -h -P now "Power button pressed"
    +
    +       if [ -x /bin/systemctl ] ; then
    +           echo "\nPower button pressed\nThe system is going down for system halt NOW!" |\
    +            /usr/bin/wall -n
    +           /bin/systemctl --force poweroff
    +       else
    +           # Normal handling.
    +           /sbin/shutdown -h -P now "Power button pressed"
    +       fi
    +
    fi
    

    and then make aliases in your ~/.bashrc:

    alias reboot='echo "The system is going down for system reboot NOW!" |\
    /usr/bin/wall -n ; /bin/systemctl --force reboot'
    
    alias poweroff='echo "The system is going down for system halt NOW!" |\
    /usr/bin/wall -n ; /bin/systemctl --force poweroff'
    
  2. Creating /etc/systemd/system/ssh-user-sessions.service with the following in it:

    [Unit]
    Description=Shutdown all ssh sessions before network
    After=network.target
    
    [Service]
    TimeoutStartSec=0
    Type=oneshot
    RemainAfterExit=yes
    ExecStart=/bin/true
    ExecStop=/usr/bin/killall sshd