Thursday, November 6, 2014

Sending SSH commands

SSH is really useful to manage unix devices from a remote place. You can be away from the console, or even do not have any console at all and still be able to enter a unix session.

Of course SSH must be enabled in the host device so that it can accept the connections, but at least in the last Debian distro for RPi this is a default.

Personally I use RPi almost always by SSH. Just at first startup of a Debian installation I can use a console for some network configuration.

As You may have seen in the starting up post, I can also avoid the console for model B or B+, as SSH is already enabled and I can retrieve RPi address looking at my router logs.

Anyway SSH could be really useful also when used to send commands without a interactive session.

To send a command using SSH You can just type something like this:

ssh 'ls -l'

This will show the list of files in home folder of the user that will be requested.

Ok, that's not exactly a non-interactive session as You have to type in the user and the password for the remote connection.

Also, the first time You try to connect to a device, You have to confirm that the host key is valid and it can be stored in a local list for all the future connections.

A little improvement can be obtained by specifying the user before the ip address. Also You can tell the system to ignore the host key:

ssh -o StrictHostKeyChecking=no pi@ 'ls -l'

That's much better, but You have no way to specify the remote password inside the SSH.

Unfortunately I did not found any way to use piping for the password, so I had to find a different solution: installing sshpass.
Just type the following:

sudo apt-get install sshpass

and after the utility has been installed You can send the SSH command by using this syntax:

sshpass -p raspberry ssh -o StrictHostKeyChecking=no pi@ 'ls -l'

Where raspberry is the (default in this case) password for the remote user.

You can of course specify more than one command with SSH, as in the following example:

sshpass -p raspberry ssh -o StrictHostKeyChecking=no pi@ 'export LANG=it_IT.UTF-8 ; df -h .'

Here, before the df command, I change the language setting to the remote session in order to receive a properly (for my needs) formatted result. This returns the SD space (total, free, used, etc.) of my remote Raspberry Pi.

Do You remember the post about turning off XBMC using command line? By using the info in this post I am able to execute those commands from another RPi, manually or using a script (actually I'm using a Python script, but this is the topic for a future post).

No comments:

Post a Comment