Sunday, October 14, 2012


Using ssh and bash together gives you a great opportunity to roll out changes and grab information from remote machines quickly and easily. Here are some syntax uses of bash+ssh that could come in handy:

1) "who" command output in remote host "micky"

$ ssh root@micky "who"
root pts/0 Jan 7 06:10 (

2) Diff two files in two different boxes

Diff-ing the /etc/hosts files

$ diff <(ssh -n root@micky cat /etc/hosts) <(ssh -n root@gilbert cat /etc/hosts)

3) Execute a script in remote server, without copying it.

"" is a simple script to extract the IP add of a box. This is how we can execute this script in a reomte box without copying the same.

$ cat | ssh root@micky /bin/sh

**Problem: Can't pass command line argument to the script. If you got a script with command line args to be excuted in remote box, I feel you have to copy the same to the remote box.

4) Suppose you want to access(query) the mysql db of remote host "micky". This is how we can achieve this.

$ ssh root@micky << ! > /usr/bin/mysql -u root
> show databases;
> !


Pseudo-terminal will not be allocated because stdin is not a terminal.

5) An example BASH script to extract some informations from a remote host using "ssh"


f_Usage() {
echo "Usage: `basename $0` "

[ -z $HOST ] && f_Usage && exit $NOARG

CMD="ssh $USR@$HOST"
rhostname="$($CMD hostname)"
echo "HostName = $rhostname"
ruptime="$($CMD uptime)"
echo "UpTime =$ruptime"
rips="$($CMD /sbin/ifconfig | sed -e '2!d' -e 's/inet//')"
echo $rips | awk '{for (i=1;i<=NF;i++) {print i")",$i}}'

Executing the script:

$ ./
HostName =
UpTime = 10:26:05 up 33 days, 18:38, 2 users, load average: 0.00, 0.00, 0.00
1) addr:
2) Bcast:
3) Mask:

No comments:

Post a Comment