Automate with Expect

Often times it is very useful to perform the same command across several switches. The most difficult portion of this process is to login to the various devices as it requires a username/password prompt.

The “expect” function within Linux provides an easy workable solution to facilitate this process.

For this example, we use 3 files:

  • A text file with a simple list of IP addresses.
  • A BASH script to run the loop to work through the list.
  • An EXPECT script to perform the actual work – called on by the BASH script.

The first file is simple – it’s just a simple txt file with a list of addresses.

The BASH script could look like this (in this case we’re referencing a list named “switch.txt”):

#!/bin/bash

while read s; do
./ssh.expect ${s}
done <switch.txt

The EXPECT script is where the work is done, in this case we’re calling SSH and performing a simple command against a Cisco device:

#!/usr/bin/expect -f

set host [lindex $argv 0]
set username username-here
set password password-here

spawn ssh -oKexAlgorithms=+diffie-hellman-group1-sha1,diffie-hellman-group14-sha1 -oStrictHostKeyChecking=no ${username}@${host}
expect "Password: "
send "${password}\r"
expect "#"
send "show ip int brief\r"
expect "#"
send "exit\r"

There you go, a simple way to push or pull information to hundreds of devices.

DavisSystem

Consolidated Notes From the Desk of Sean Davis.


Simple automation using expect

By Sean, 2022-02-28