Using “Expect” in UNIX Script

There is a request to create script. The idea is to send some commands to the routers (around 16 routers in total) from remote Unix server and save the outputs to file.

The problem is, this routers haven’t had capability yet for password less setup by using key exchange which is more secure.

There were several options, but all of them are using password “hardcoded”, meaning the password of the router must be written inside the script.

Finally, “expect” is chose, since it is already installed in the remote Unix server. Moreover, according to rule in the company, any additional software package can not be installed unless there is approval.

Below are codes. Let’s name it as getoutput and make it to be executable.

#!/usr/local/bin/expect -f

set uu "<username>"
set pp "<password>"

set hh [lindex $argv 0]

spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no $uu@$hh

expect "*password*"
send -- "$pp\r"
expect "*>*"
send -- "<1st command >"
send -- "\r"
expect "*>*"
send -- "<2nd command>"
send -- "\r"
expect "*>*"
send -- "<3rd command>"
send -- "\r"
send -- "<4th command>"
send -- "\r"

# done
expect eof

Then loop above script to be executed for all routers.

#!/bin/bash
for router in `cat routers_ip_file`; do getoutput $router > $router.outputfile.log; done

Note:

There are StrictHostKeyChecking and CheckHostIP parameters whose value as “no” inside above script. Actually the purpose is to avoid host checking prompt, if the ssh session is performed for the first time to destination host.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s