Monday, April 22, 2013

One-liner to shutdown remote host

To shutdown the local machine immediately, you execute this command as root or under sudo:
$ shutdown -h now

If it is a remote server that you want to shutdown, it could be slightly more involved.

You need to have root privileges to shutdown a machine. However, many systems are configured to block root from logging in remotely usingssh. So, you need to ssh in as a regular, non-root user, and pass the sudo command to shutdown host.

$ ssh -t peter@ 'sudo shutdown -h now'
peter@'s password: 
[sudo] password for peter: 
Broadcast message from root@tiger (pts/2) (Sat Apr 13 10:56:30 2013):

The system is going down for system halt NOW!
Connection to closed.

Don't forget the -t sshparameter to "force pseudo-tty allocation". Without it, the above one-liner will fail with this message.

sudo: no tty present and no askpass program specified

Note that you will be prompted twice to type in your password. The first time is for ssh; the second, sudo.

To avoid typing the first password, set up password-less login. This is a topic by itself, and I won't go into it here.

To avoid the second, configure sudo to not prompt peter for his password when he issues a sudo command. This is done by editing the /etc/sudoers file.

$ visudo

Insert the following line to the file:


The above line allows peter to sudo as anybody from any host and run any command without being authenticated. Only do this after you have considered its security ramifications. You have been forewarned.

Now run the one-liner again.

$ ssh -t peter@ 'sudo shutdown -h now'
peter@'s password: 

Broadcast message from root@tiger (pts/1) (Sat Apr 20 21:40:50 2013):

The system is going down for system halt NOW!
Connection to closed.
The user is only prompted once, by ssh, to enter a password.


Anonymous said...

or to do it as a batch job
for a in host1 host2 host3;do
ssh $a 'echo "sudo shutdown -h now" | at now'

Peter said...

Fantastic! The "-t" parameter is exactly what I needed today for performing a remote login through a proxy host ($ ssh -t "ssh").

Looks like whenever I have a problem to solve on the command line LinuxCommando comes in to give me a helping hand!

Thanks Peter!
Yours ... Peter!

Replica Soccer Jersey said...


Anonymous said...

Nice Information.. Thanks for your efforts.