Expect Scripting Tutorial With Examples – POFTUT

Expect Scripting Tutorial With Examples


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.

  • send to send strings to the process
  • expect wait for the specific string from the process
  • spawn to 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
Expect Script Installation
Expect Script Installation

Syntax

We will use following syntax for expect command.

expect [ -dDinN ] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ]

Usage

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/expect line 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 poftut to continue. If poftut text is not provided the script file will not jump to next line.
  • send "com" will send to remote device or current output the com string.

We can test our script in the current bash by providing the script file name like exp1.sc

$ expect exp1.sc
Expect Usage
Expect Usage

Timeout

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
Timeout
Timeout

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 "ismail@localhost's password: " 
 
send "123456" 
 
expect "ismail@ubu2:~$" 
 
send "uname -a"
  • spawn ssh localhost will connect to the localhost with ssh protocol.
  • expect "ismail@localhost's password: " will expect for the specified text.
  • send "123456" is used to send password for the ssh connection
LEARN MORE  What Is Telnet Command and What Is Telnet Used For?

2 thoughts on “Expect Scripting Tutorial With Examples”

Leave a Comment