Tuesday, April 23, 2013
7:11 AM

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@192.168.1.112 'sudo shutdown -h now'
peter@192.168.1.112'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 192.168.1.112 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:


peter ALL=(ALL) NOPASSWD: ALL

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@192.168.1.112 'sudo shutdown -h now'
peter@192.168.1.112'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 192.168.1.112 closed.
The user is only prompted once, by ssh, to enter a password.

0 comments:

Post a Comment