Expect Command in Linux


I was trying to automate a few things here for office & the search took me to a utility called “Expect”. Expect can be used to automate a variety of tasks where you know what should be the output & hence it allows you to feed the correct input 🙂 Put all this in a chain & voila! You got the job done. Below is a very simple script that makes use of Expect. Make sure, you install expect package first.

yum install expect* -y
!/usr/bin/sh
spawn ssh shashank@server
expect "shashank@$server's password: "
send "Password" #This is your real password, so make sure you don't give any rights to this script to anyone. Root is god, obviously ;)
expect "$ "
send "hostname\r"
expect "$ "
send "exit\r"

Below is the brief explanation of the script/Expect.

spawn – Executes the command. In this case, its establishing an SSH connection to my machine using my user-id.

expect – What output will you see when you try to SSH into a server? yes, it prompts for a password.

send – Sends the password (input) to the question (output).

expect – Since the password has been supplied, there will b a $ prompt (obviously a normal user’s). It means we have logged in with the user-id.

send – This time it sends the command that needs to be executed on that server. In this case, its just the hostname. \r means execute the command & return (press enter).

expect – We can expect to see a $ prompt again since enter has been pressed (\r).

send – Issues exit command to log out.

To run this script, issue :-

#expect /path_to_/expect.sh

Advertisements

2 thoughts on “Expect Command in Linux

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