SSH with expect in BASH, Perl, Python

Posted on Sat 17 September 2011 by Pavlo Khmel

There are special modules for Perl/Python for SSH connection. For example:
Net::SSH2::Expect
Net::SSH::Expect
In BASH can be used SSH with Public key, cssh (Cluster SSH), sshpass, Example: sshpass -p 'PASSWORD' ssh pavlo\@10.10.10.10 'ls -l /tmp/temp_file.txt'.
But examples below are with Expect (for sudo and another commands).

Input

$ ./sshauto.sh 'ls -l /etc/redhat-release'
$ ./sshauto.pl 'ls -l /etc/redhat-release'
$ ./sshauto.py 'ls -l /etc/redhat-release'

Output

Password:
pavlo@10.10.10.10's password:
-rw-r--r--  1 root root 56 Jul 19  2006 /etc/redhat-release
pavlo@20.20.20.20's password:
-rw-r--r--  1 root root 56 Jul 19  2006 /etc/redhat-release
pavlo@30.30.30.30's password:
-rw-r--r--  1 root root 56 Jul 19  2006 /etc/redhat-release

IP address list in file:

$ cat ip_addresses.txt
10.10.10.10
20.20.20.20
30.30.30.30

BASH

Install: expect

$ cat ./sshauto.sh
#!/bin/bash
echo -n "Password:"
read -s passw; echo
stty echo
while read IP
do
./sshlogin.exp $passw $IP "$1" 2> /dev/null
done < ip_addresses.txt

$ cat ./sshlogin.exp
#!/usr/bin/expect -f
set password [lrange $argv 0 0]
set ip_address [lrange $argv 1 1]
set command [lindex $argv 2]
spawn ssh -q -t -o ConnectTimeout=5 -o StrictHostKeyChecking=no phn@$ip_address $command
expect "*?assword:*"
send -- "$password\r"
expect eof

PERL

Install:

$ cpan install Expect
$ cpan install Term::ReadKey

Script:

$ cat ./sshauto.pl
#!/usr/bin/perl
use Expect;
use Term::ReadKey;
print "Password:";
ReadMode ''noecho'';
$password = ReadLine(0);
chomp($password);
print "\n";
ReadMode ''normal'';
$command = $ARGV[0];
open (IP_list, ''ip_addresses.txt'');
foreach $IP (<IP_list>) {
    chomp($IP);
    $cli = "/usr/bin/ssh -q -t -o ConnectTimeout=5 -o StrictHostKeyChecking=no phn\@$IP  $command";
    $exp = new Expect;
    $exp->raw_pty(1);
    $exp->spawn($cli) or die "Cannot spawn $cli: $!\n";
    $exp->expect(5, [ qr /ssword:*/ => sub { my $exph = shift; $exph->send("$password\n"); exp_continue; }] );
};
close (IP_list);

Python

Install: pexpect

$ cat ./sshauto.py
#!/usr/bin/python
import pexpect
import getpass
import sys
command = sys.argv[1]
password = getpass.getpass()
IP_list = open("ip_addresses.txt")
IP = IP_list.readline()
while IP:
    print IP,
    cli="ssh phn@%s %s" % (IP,command)
    exp = pexpect.spawn(cli)
    exp.expect("password:")
    exp.sendline(password)
    exp.expect(pexpect.EOF)
    print exp.before
    IP = IP_list.readline()
IP_list.close()