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 user@hostname command
For example login into remote system called portal.nixcraft.com and find out who logged in, enter:
$ ssh email@example.com 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 sshscript.sh
Type the following shell script lines:
#!/bin/bash # Linux/UNIX box with ssh key based login enabled SERVER="192.168.1.1" # SSH User name USR="admin" OUT="out.txt" ssh $USR@$host w > $OUT
Save and close the file. Type the following command to execute the script:
$ chmod +x sshscript.sh
You can see output of script with cat command:
$ cat out.txt
See more complex example in our shell script directory.