Sunday, October 14, 2012

SSH+Bash


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"

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


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

No comments:

Post a Comment