Sunday, March 10, 2013

Automated remote Linux Login Expect script

The following script is my example of using Expect to automate login and command execution from a Linux box to another server using SSH

Script command line argument = hostname / IP address



#!/usr/bin/expect

set LOGDIR   "./"

###########################################################################

set USER matt
set PASS mattspassword
set HOST [lindex $argv 0]
set PORT 22
set TIMEOUT 180
set PROMPT "# "

###########################################################################

log_file -a $LOGDIR/$HOST.log

catch { spawn ssh -p $PORT $HOST -l $USER }
set timeout $TIMEOUT

expect {

        timeout         {
                        send_user "\nTIMED OUT $TIMEOUT seconds\n";
                        exit 0;
                        }

        "yes/no"        {
                        sleep 1;
                        send "yes\r";
                        exp_continue;
                        }

        "*assword:"     {
                        sleep 1;
                        send "$PASS\r";
                        }
}


expect {

        "*assword:"     {
                        sleep 1;
                        send_user "\nWRONG PASSWORD or LOGIN DISABLED\n";
                        exit 0;
                        }

        # This is where we do the work

        "$PROMPT"       {
                        sleep 1;
                        send "\r";
                        expect "$PROMPT";
                        send "uname -a\r"
                        expect "$PROMPT";
                        send "echo \"my public ssh key infoz\" >> ./tempfile.cert\r"
                        expect "$PROMPT";
                        send "exit\r";
                        exit 1;
                        }
}

No comments:

Post a Comment