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:

Ubuntu, Debian, Kali, Mint:

Expect Script Installation

Expect Script Installation


We will use following syntax for expect command.


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

Expect Usage


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.

LEARN MORE  Useful Linux Commands A System Administrator Should Know

echo '

We do not enter any value for this expect script and after 5 second next step is evaluated.



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 .

  • 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

2 Responses

  1. clarkw says:

    take a look at https://github.com/clarkwang/sexpect . you can write expect scripts with shells only.

  1. 27/02/2018

    […] en.wikipedia.org pantz.org thegeekstuff.com poftut.com admin-magazine.com […]

Leave a Reply

Your email address will not be published. Required fields are marked *