pythonsshparamikocisco

Execute several commands on Cisco switch via Paramiko - improve performance


I'm trying to login into a cisco switch and do some stuff there (configure a port for example). I can't use exec_command(cmd1 \n cmd2 \n) on cisco devices apparently... So I'm using a channel to send my commands on like so:

channel = ssh.invoke_shell()
channel.send("show arp\n")
while not channel.recv_ready():
    time.sleep(0.5)
out = channel.recv(9999)

I don't like the time.sleep(0.5) and want something to dynamicaly wait for the command to be executed because sometimes commands take even longer than 0.5sec and that would slow down everything a lot. With exec_command(cmd) I had exit_status = channel.recv_exit_status()for example.

Is there a way around this?


Could I somehow listen to the channel and wait for the output to be like

CISCOSWITCH#

so that I know that I'm ready to send more commands or exit?


I cannot use exec_command, because that closes the channel and when my intent is to configure a port I have to send multiple commands in the same session. (I think that's how it works)


Solution

  • In general you should use an "exec" channel for this. The "shell" channel should not be used to automate a command execution.

    But I understand that your server does not support multiple commands with the "exec" channel. I've added the above comment for the other readers, not to try to use this solution, unless they really have to.


    If you have to use the "shell" channel, you have to use shell techniques.

    So in your particular case, you may want to have the remote shell print some unique string after the command finishes:

    channel.send("show arp\necho Command-has-finished\n")
    

    Then you keep reading the output until you find a line "Command-has-finished".

    Check the reading code from JSch Exec.java example.