Write an SIE script in Expect
Expect drives interactive programs: it waits for text, then sends a reply. That makes it the tool for devices that need a password typed at a prompt, menus, “press any key” screens, pagers and serial consoles. It’s written in Tcl, which takes a little getting used to.
Good for
- Password logins over SSH or Telnet.
- Menus, notices, pagers and anything else a person would have to answer.
- Serial consoles through a console server.
If Netmiko already supports the device, it saves writing the conversation by hand.
Set it up
sudo dnf install expect # RHEL familysudo apt install expect # Ubuntuwhich expect # use this path in the commandThe command
/usr/bin/expect {script_path}my-script.exp {device_ip} {device_username} {device_password}A minimal script
#!/usr/bin/expect -f## Minimal SIE script in Expect: password login over SSH, one command.## Usage: expect-skeleton.exp <ip> <username> <password>
set keys "/var/www/html/rconfig8/current/storage/app/rconfig/scripts/keys"set prompt_re {[>#] ?$}
proc fail {message} { puts stderr "ERROR: $message"; exit 1 }
if {[llength $argv] < 3} { fail "usage: expect-skeleton.exp <ip> <username> <password>" }lassign $argv ip user pwd
log_user 0 ;# keep the session off stdoutmatch_max 1000000 ;# room for long outputset timeout 20
spawn ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=$keys/known_hosts $user@$ipexpect { -re {(?i)password:} { send -- "$pwd\r"; exp_continue } -re {(?i)(denied|incorrect|failed)} { fail "login failed for $user@$ip" } -re $prompt_re {} timeout { fail "timed out logging in to $ip" } eof { fail "connection to $ip closed" }}
send -- "terminal length 0\r"expect -re $prompt_re
set timeout 60send -- "show running-config\r"expect { -re $prompt_re { set raw $expect_out(buffer) } timeout { fail "timed out waiting for the config" }}send -- "exit\r"
regsub -all {\r} $raw "" rawset config [string trim [join [lrange [split $raw "\n"] 1 end-1] "\n"]]if {$config eq ""} { fail "no output from $ip" }
puts $configputs stderr "SIE-OK: expect [llength [split $config "\n"]] lines from $ip"exit 0Habits that matter in Expect
log_user 0first. Otherwise the whole session (banner, password prompt, echoed commands) goes to stdout and is stored.putsfor the config,puts stderrfor everything else.send_userwrites to stdout, so don’t use it for progress messages.match_max. The default buffer is 2000 bytes. Longer output loses its beginning without warning.- A
timeoutandeofbranch on everyexpectthat matters. Without them, a missed prompt silently falls through to the next line. --aftersend.send -- "$pwd\r"stops a password that starts with-being read as an option.