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@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.

Friday, April 19, 2013

One-liner to copy text to a remote host

Occasionally, I want to copy a short line of text to a remote computer. For instance, I have an URL for some real cool web site which, for whatever reason, I want to send to a remote host. I can always put the text in a file, and transfer it via scp.

$ cat > coolurl.txt
http://really-cool-web-site/

$ scp coolurl.txt peter@192.168.1.112:

Or, you can use the following one-liner command:

$ echo 'http://really-cool-web-site/'|ssh peter@192.168.1.112 'cat >coolurl.txt'

The one-liner uses only simple commands such as echo, ssh and cat. It saves you the step of creating a new file on the local machine.

The text is saved to a file called coolurl.txt on the remote computer under your home directory.

Let me know your favourite way to accomplish the same thing.