Thursday, April 19, 2007

Trapping signals (^C and ^Z) in Bash

#!/bin/bash
#Script written by Vaibhav Gupta
#Trapping HUP TERM INT and ^Z in shell.

echo "Process ID = $$";
stty susp "" #Trapping CTRL-Z
trap 'echo "Trapping CTRL-C, TERM and HUP";' HUP TERM INT
echo

echo "Sleeping for some time"
for i in `seq 1 20`; do
    sleep 1
    echo -n "."
done
echo
stty susp "^Z"


Koool bash Functions


http://www.novell.com/coolsolutions/tools/18639.html

Tuesday, April 17, 2007

Script to exchange ssh keys

 1 #!/usr/bin/perl
2 use Expect;
3 #USAGE: ssh-key-exchange.pl <IP> <USERNAME> <PASSWORD>
4
5 my $ip = $ARGV[0];
6 my $login = $ARGV[ 1];
7 my $password = $ARGV[2 ];
8 my $private_key='/root/.ssh/id_rsa ';
9 my $public_key='/root/.ssh/id_rsa.pub ';
10 my $authorisedkeyfile='/root/.ssh/authorized_keys ';
11 my $timeout = 10;
12 my $aft = new Expect;
13
14 #Generate the public and private key on the local m/c A
15 if(!(( -e $public_key ) &&( -e $private_key ))) {
16 print "Generating the Public and Private Key:\n ";
17 @result=`ssh-keygen -t rsa -f /root/.ssh/id_rsa -P "" `;
18 #print @result;
19 }
20 #Copy the file to m/c B
21 print "Copying Public Key from A to B.\n ";
22 $aft->spawn("scp $public_key $login\@$ip:/tmp/");
23 $aft->expect($timeout,[ qr'\? $' , sub { my $fh=shift; $fh->send("yes\n"); exp_continue; } ],
24 [ 'Password: $',sub { my $fh=shift;$fh->send("$password \n");exp_continue;} ],
25 # '-re','\# $'
26 );
27 $aft->do_soft_close();
28
29
30 #Add Keys to authorised keys in B
31 print " Adding Keys to authorised key in B with IP=$ip,[ $login $password ] \n";
32 my $aft = new Expect;
33 $aft->log_file("/tmp/expect_log" ,"w");
34 $aft->spawn( "ssh $login\@$ip") or die "Cannot ssh to the machine \n";
35 $aft->expect($timeout,[ qr'\? $', sub { my $fh=shift;$fh ->send("yes\n"); exp_continue; } ],
36 [ 'Password: $',sub { my $fh=shift;$fh->send("$password\n ");exp_continue;} ],
37 '-re', '\# $'
38 );
39 $aft ->send("touch $authorisedkeyfile\n");
40 $aft->expect($timeout,'-re' ,'\# $');
41 $aft->send( "cat /tmp/id_rsa.pub >> $authorisedkeyfile\n");
42 $aft->expect($timeout,'-re', '\# $');
43 $aft->send(" exit\n");
44 $aft->do_soft_close();
45