How To Use SSH in Unix or Linux shell script

Q. How do I use ssh client program in a shell script under UNIX or Linux operating system?

A. SSH client is a program for logging into a remote machine and for executing commands on a remote machine. ssh connects and logs into the specified hostname.The user must prove his/her identity to the remote machine using one of several methods depending on the protocol version used. If command is specified, command is executed on the remote host instead of a login shell.

SSH general syntax

ssh [email protected] command

For example login into remote system called and find out who logged in, enter:
$ ssh [email protected] who
You can use same command in shell script. However, it will prompt for a password. To avoid password prompt you need to ssh keys based login as specified in our article for password less login. Next, you can create a sample shell script as follows:

$ vi

Type the following shell script lines:

# Linux/UNIX box with ssh key based login enabled
# SSH User name
ssh $USR@$host w > $OUT

Save and close the file. Type the following command to execute the script:
$ chmod +x
$ ./

You can see output of script with cat command:
$ cat out.txt
See more complex example in our shell script directory.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.