Configuration Guide Vol. 1


21.4.1 Setting of specified command execution

This section explains how to use commandline module to execute the specified command.

Commandline module has a CommandLine class that executes configuration and operation commands from scripts. The following tables list the methods for CommandLine classes.

Table 21-15 List of Methods of the CommandLine Class

Method name

Description

exec

Executes the command specified in the argument.

exit

Terminates command execution by the instance.

set_default_timeout

Sets the default timeout period when the command is executed by the target instance.

set_default_logging

Specifies whether or not the operation command show logging is to be displayed for logging commands executed from the target instance.

<Structure of this section>

(1) Script file and execution results example

(a) Examples of executing various commands

Here is an example of a script file that executes various commands:

Figure 21-15: Example of writing a script file (sample1.py)
# sample1.py
# -*- coding: utf-8 -*-
import extlib.commandline                                             ..1
obj = extlib.commandline.CommandLine()                                ..2
 
# Specify default timeout
obj.set_default_timeout(180)                                          ..3
 
# Specify default non-display of command log show logging
obj.set_default_logging(extlib.commandline.DISABLE)                   ..4
 
# User-unresponsive command (ls) 
print("ls start")
dict_ret = obj.exec("ls")                                             ..5
if dict_ret['result'] == extlib.commandline.OK:
    print(dict_ret['strings'])                                        ..6
else:
    print("timeout.")
 
# Command with user response (delete file1, file2) 
print("rm start")
dict_ret = obj.exec("rm -i file1 file2", ("?","y"), ("?", "y"),
                     logging=extlib.commandline.ENABLE)               ..7
if dict_ret['result'] == extlib.commandline.OK:
    print(dict_ret['strings'])                                        ..8
else:
    print("timeout.")
 
# Specify command response timeout period (ping for 3 sec) 
print("ping start")
dict_ret = obj.exec("ping 192.0.2.1", 3)                              ..9
if dict_ret['result'] == extlib.commandline.TIMEOUT:
    print(dict_ret['strings'])                                        ..10
obj.exit()                                                            ..11
  1. Import the module.

  2. Creates an instance of CommandLine.

  3. Specifies the default timeout period for command responses.

  4. Hides the default show logging display setting for the command log.

  5. In exec method, specify the command to be executed (no user response).

  6. Outputs the command execution result.

  7. In exec method, specify the command to be executed (with user response) and show logging view setting (display) of the command log.

  8. Outputs the command execution result.

  9. In exec method, specify the timeout period for the command to be executed and the command response.

  10. Outputs the command execution result.

  11. Ends the command execution status.

The script file sample1.py executes as follows: The operation-command ls,rm, and ping specified in exec method are executed correctly.

Figure 21-16: Result of executing a script (sample1.py)
# python sample1.py
ls start
file1 file2
 
rm start
remove 'file1'? remove 'file2'?
ping start
PING 192.0.2.1 (192.0.2.1): 56 data bytes
64 bytes from 192.0.2.1: icmp_seq=0 ttl=63 time=0.377 ms
64 bytes from 192.0.2.1: icmp_seq=1 ttl=63 time=0.545 ms
64 bytes from 192.0.2.1: icmp_seq=2 ttl=63 time=1.349 ms
64 bytes from 192.0.2.1: icmp_seq=3 ttl=63 time=0.578 ms
 
----192.0.2.1 PING Statistics----
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.377/0.858/1.385/0.445 ms
 
#

(b) Examples of Errors During Script Execution

The following is an example of specifying an invalid value for the command response timeout time.

Figure 21-17: Example of writing a script file (sample2.py)
# sample2.py
# -*- coding: utf-8 -*-
import extlib.commandline                                             ..1
obj = extlib.commandline.CommandLine()                                ..2
 
# Command response timeout period (negative number is specified for time)
print("ping start")
dict_ret = obj.exec("ping 192.0.2.1", -3)                             ..3
print(dict_ret['strings'])                                            ..4
 
obj.exit()                                                            ..5
  1. Import the module.

  2. Creates an instance of CommandLine.

  3. In exec method, specify the timeout (negative) between the command to be executed and the command response.

  4. Outputs the command execution result.

  5. Ends the command execution status.

The script file sample2.py executes as follows: An error occurs because the value specified for the timeout period is incorrect.

Figure 21-18: Result of executing a script (sample2.py)
# python sample2.py
ping start
Traceback (most recent call last):
  File "sample2.py", line 7, in <module>
    dict_ret = obj.exec("ping 192.0.2.1", -3)
  File "/usr/local/lib/python3.2/site-packages/extlib/commandline.py", line 741, in exec
    CNST.ERR_TIMER_INVALID))
ValueError: The timer value is invalid.
#

(c) Example of Command Execution Failure Exception

Here is an example of regenerating an instance when exec method encounters a command execution failure exception:

Figure 21-19: Example of writing a script file (sample3.py)
# sample3.py
# -*- coding: utf-8 -*-
import extlib.commandline                                             ..1
obj = extlib.commandline.CommandLine()                                ..2
 
retry_cnt = 0
 
# Command without user response (ls) 
print("ls start")
while retry_cnt < 3:
    try:
        dict_ret = obj.exec("ls")                                     ..3
        if dict_ret['result'] == extlib.commandline.OK:
            print(dict_ret['strings'])                                ..4
            print("success!!")
        else:
            print("timeout.")
        break
    except extlib.commandline.ExecuteCommandError:                    ..5
        obj.exit()                                                    ..6
        obj = extlib.commandline.CommandLine()                        ..7
        print("Regenerate the instance")
        retry_cnt = retry_cnt + 1
 
obj.exit()                                                            ..8
  1. Import the module.

  2. Creates an instance of CommandLine.

  3. In exec method, specify the command to be executed (no user response).

  4. Outputs the command execution result.

  5. Captures exceptions for failed command executions in exec method.

  6. Exits the command execution status.

  7. Regenerate CommandLine instances.

  8. Ends the command execution status.

The script file sample3.py executes as follows: Even if an exception occurs, the operation-command ls is executed correctly because the instance was regenerated.

Figure 21-20: Result of executing a script (sample3.py)
# python sample3.py
ls start
Regenerate the instance
file1 file2
 
success!!
#

(2) Instantiation

You cannot create more than one instance of CommandLine class for a single process. When you regenerate an instance, call exit method on the existing instance first.

(3) Executing Commands in exec Method

If you use exec method of commandline module to execute the command, the script-only user (username script) executes the corresponding command. The following tables show how to execute commands using exec method.

Table 21-16 Executing Commands Using the exec Method

Item

Description

Initial command input mode

User mode

Invalid command

For script-only users, setting changes made by executing the following operation commands are ignored:

  • set exec-timeout

  • set terminal pager

The following configuration commands for script-only users are invalid:

  • Logging-console Parameters for username Commands

  • Exec-timeout Parameters for username Commands

  • Terminal-pager Parameters for username Commands

(4) Command Approval

If command authorization is set for the Switch, command authorization is also applied to commands executed from scripts.

Commands executed from scripts are approved with the privilege of the username specified in username parameter of the configuration command aaa authorization commands script. If bypass parameter is specified, the command can be executed unconditionally without command authorization.

The following are special notes about command authorization: