Using the CLI Library to Run an Interactive Command
To run interactive commands, three phases are needed:
•
Phase 1: Issue the command using the cli_write command extension.
•
Phase 2: Q&A Phase. Use the cli_read_pattern command extension to read the question (the regular
pattern that is specified to match the question text) and the cli_write command extension to write back
the answers alternately.
•
Phase 3: Noninteractive phase. All questions have been answered, and the command will run to
completion. Use the cli_read command extension to wait for the complete output of the command and
the device prompt.
For example, use CLI commands to do squeeze bootflash: and save the output of this command in the Tcl
variable cmd_output.
if [catch {cli_open} result] {
error $result $errorInfo
} else {
array set cli1 $result
}
if [catch {cli_exec $cli1(fd) "en"} result] {
error $result $errorInfo
}
# Phase 1: issue the command
if [catch {cli_write $cli1(fd) "squeeze bootflash:"} result] {
error $result $errorInfo
}
# Phase 2: Q&A phase
# wait for prompted question:
# All deleted files will be removed. Continue? [confirm]
if [catch {cli_read_pattern $cli1(fd) "All deleted"} result] {
error $result $errorInfo
}
# write a newline character
if [catch {cli_write $cli1(fd) "\n"} result] {
error $result $errorInfo
}
# wait for prompted question:
# Squeeze operation may take a while. Continue? [confirm]
if [catch {cli_read_pattern $cli1(fd) "Squeeze operation"} result] {
error $result $errorInfo
}
# write a newline character
if [catch {cli_write $cli1(fd) "\n"} result] {
error $result $errorInfo
}
# Phase 3: noninteractive phase
# wait for command to complete and the router prompt
if [catch {cli_read $cli1(fd) } result] {
error $result $errorInfo
} else {
set cmd_output $result
}
if [catch {cli_close $cli1(fd) $cli1(tty_id)} result] {
error $result $errorInfo
}
The following example causes a device to be reloaded using the CLI reload command. Note that the EEM
action_reload command accomplishes the same result in a more efficient manner, but this example is presented
to illustrate the flexibility of the CLI library for interactive command execution.
# 1. execute the reload command
Consolidated Platform Configuration Guide, Cisco IOS Release 15.2(4)E (Catalyst 2960-X Switches)
1858
cli_write