Date created: Thursday, May 22, 2014 10:23:49 PM. Last modified: Thursday, May 22, 2014 10:23:49 PM

Cisco Watch

A simple expect script to log into a Cisco device and repeatedly run a command and print the date and time each time it is executed, like the unix watch command.

cisco-watch.sh

#!/usr/bin/expect

# Expect script to repeatedly run the same command
# by jwbensley@gmail.com
# If you don't like it, fuck off.

# Long delay for those tricky hostnames

set timeout 60

# Prompt user for device name/IP address, username, password, 
# and command to run (example: show cdp neigh)

send_user "Device name: "
expect_user -re "(.*)\n"
set host $expect_out(1,string)

send_user "Username: "
expect_user -re "(.*)\n"
set user $expect_out(1,string)

# Don't show the password it is typed
stty -echo
send_user "Password: "
expect_user -re "(.*)\n"
set pass $expect_out(1,string)
send_user "\n"
stty echo

send_user "Enable mode by default \[yes\/no\]: "
expect_user -re "(.*)\n"
set enable $expect_out(1,string)
# Expect enable mode by default
if { $enable == "" } {
 set enable "yes"
}

send_user "SSH or telnet \[ssh\/telnet\]: "
expect_user -re "(.*)\n"
set protocol $expect_out(1,string)
# Use SSH as default
if { $protocol == "" } {
  set protocol "ssh"
}

send_user "command: "
expect_user -re "(.*)\n"
set command $expect_out(1,string)
if { $command == "" } {
  send_user "Need interface name\!\n"
  exit
}

send_user "Interval in seconds \[3\]: "
expect_user -re "(.*)\n"
set delay $expect_out(1,string)
# Use 3 seconds as the default execution delay if none is given
if { $delay == "" } {
  set delay 3
}
send_user "\n"


# Connect to the host and login
if { $protocol == "ssh" } {
  spawn ssh $host -l $user
  # Expect "assword:" as the 'p' in 'password' could be upper or lower case
  expect "assword:"
  send "$pass\r"
  if { $enable == "yes" } {
   expect "#"
  } else {
   expect ">"
  }
  puts ""
} else {
  spawn telnet $host
  expect "Username:"
  send "$user\r"
  # Expect "assword:" as the 'p' in 'password' could be upper or lower case
  expect "assword:"
  send "$pass\r"
  if { $enable == "yes" } {
   expect "#"
  } else {
   expect ">"
  }
  puts ""
}

# From this point on we shall disable user output or they will see the command being run repeatedly 
log_user 1

# Enter a continuous loop to repeatedly run the command

while { true } {

  set datet [exec date +%d-%m-%y--%H:%M:%S]
  send_user "$datet\n"
  #exec date +%d-%m-%y--%H:%M:%S

  send "$command\r"
  if { $enable == "yes" } {
   expect "#"
  } else {
   expect ">"
  }

  send_user "\n\n"

  sleep $delay
}

Previous page: Host Interface Throughput
Next page: Git