Wednesday, January 23, 2008

using SSH from BASH


A few extra uses of ssh in BASH.

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


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


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.

"getipline.sh" 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 getipline.sh | ssh root@micky /bin/sh
addr:192.168.32.8


**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;
> !


Output:

Pseudo-terminal will not be allocated because stdin is not a terminal.
Database
mysql
test
NMS


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


#!/bin/sh
SSH="/usr/bin/ssh"
HOST=$1
USR=${2:-root}
NOARG=65

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:


$ ./fetch.sh 172.22.22.121
HostName = gentle.crp.xyz.com
UpTime = 10:26:05 up 33 days, 18:38, 2 users, load average: 0.00, 0.00, 0.00
1) addr:172.22.22.121
2) Bcast:172.22.0.255
3) Mask:255.255.255.0

2 comments:

eriol said...

But all this of course if you have shared keys.
Otherwise you'll be prompted for passwords at all tmes, right ?

Unknown said...

@eriol, yes you are right, the public-private key configuration needs to be there. Thanks for visiting unstableme.

© Jadu Saikia www.UNIXCL.com