Expect is a scripting language used to automate interactive shells. For example if we want to automate Cisco devices over a shell by using some expect scripting. Expect scripting generally works on specified strings. Most used expect commands are like below.
sendto send strings to the process
expectwait for the specific string from the process
spawnto start new command
Expect Script Installation
Expect have a shell to interpret and execute expect commands. Most Linux distributions do not installs by default this package.
Fedora, Cent OS, Red Hat:
$ sudo yum install expect
Ubuntu, Debian, Kali, Mint:
$ apt install expect
We will use following syntax for
expect [ -dDinN ] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ]
Expect generally reads scripts from a script file. Now we will create a simple script which can be used to login a Cisco device. Our script file is like below.
#!/usr/bin/expect expect "poftut" send "com"
#!/usr/bin/expectline is used to set expect as interpreter for this script. This can be omitted if we are providing this script file directly to the expect interpreter but using this will make script file more readable.
expect "poftut"line used to express we expect script
poftutto continue. If
poftuttext is not provided the script file will not jump to next line.
send "com"will send to remote device or current output the
We can test our script in the current bash by providing the script file name like
$ expect exp1.sc
There is a timeout for performance issues. Timeout is used to set maximum time to be wait for a connection or response. If the timeout value is reach the next step will be evaluated. Timeout value can be set with
set timeout command. In this example we will set time out 5 second.
#!/usr/bin/expect set timeout 5 expect "poftut" send "com"
We do not enter any value for this expect script and after 5 second next step is evaluated.
$ expect exp1.sc
Spawn External Process
Now we may want to use external tools like ssh to connect remote hosts and run expect scripts on the remote. Now we will create a ssh connection to the remote host and enter a password .
#!/usr/bin/expect set timeout 5 spawn ssh localhost expect "[email protected]'s password: " send "123456" expect "[email protected]:~$" send "uname -a"
spawn ssh localhostwill connect to the localhost with ssh protocol.
expect "[email protected]'s password: "will expect for the specified text.
send "123456"is used to send password for the ssh connection