- To connect to a remote host with the SSH server running, use the following command:
$ ssh username@remote_host
The options in this command are as follows:
- username is the user that exists at the remote host
- remote_host can be the domain name or IP address
Consider this example:
$ ssh mec@192.168.0.1
The authenticity of host '192.168.0.1 (192.168.0.1)' can't be
established.
RSA key fingerprint is
2b:b4:90:79:49:0a:f1:b3:8a:db:9f:73:2d:75:d6:f9.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.0.1' (RSA) to the list of
known hosts.
Password:
Last login: Fri Sep 3 05:15:21 2010 from 192.168.0.82
mec@proxy-1:~$
SSH will ask for a password, and upon successful authentication it will connect to the login shell on the remote machine.
By default, the SSH server runs at port 22. However, certain servers run SSH service at different ports. In that case, use -p port_num with the ssh command to specify the port.
- Connect to an SSH server running at port 422:
$ ssh user@locahost -p 422
When using ssh in shell scripts, we do not want an interactive shell, we simply want to execute commands on the remote system and process the command's output.
- To run a command at the remote host and display its output on the local shell, use the following syntax:
$ sshuser@host 'COMMANDS'
Consider this example:
$ ssh mec@192.168.0.1 'whoami'
mec
You can submit multiple commands by separating the commands with a semicolon:
$ ssh user@host "command1 ; command2 ; command3"
Consider the following example:
$ ssh mec@192.168.0.1 "echo user: $(whoami);echo OS: $(uname)"
Password:
user: mec
OS: Linux
In this example, the commands executed at the remote host are as follows:
echo user: $(whoami);
echo OS: $(uname)
We can pass a more complex subshell in the command sequence using the ( ) subshell operator.
- The next example is an SSH-based shell script to collect the uptime of a list of remote hosts. Uptime is the length of time since the last power-on. It's returned by the uptime command.
It is assumed that all systems in IP_LIST have a common user test.
#!/bin/bash
#Filename: uptime.sh
#Description: Uptime monitor
IP_LIST="192.168.0.1 192.168.0.5 192.168.0.9"
USER="test"
for IP in $IP_LIST;
do
utime=$(ssh ${USER}@${IP} uptime |awk '{ print $3 }' )
echo $IP uptime: $utime
done
Expected output:
$ ./uptime.sh
192.168.0.1 uptime: 1:50,
192.168.0.5 uptime: 2:15,
192.168.0.9 uptime: 10:15,