【问题标题】:Paramiko session times out, but i need to execute a lot of commandsParamiko 会话超时,但我需要执行很多命令
【发布时间】:2021-03-23 14:10:58
【问题描述】:

我正在编写一个脚本(python 2.7),它与运行 Cisco IOS 的远程设备一起工作,所以我需要通过 ssh 执行很多命令。 很少有命令没有输出,其中一些有,我想接收输出。它是这样的:

import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self._ip, port=22, username=username, password=password
stdin, stdout, stderr = ssh.exec_command('command with no output')
stdin, stdout, stderr = ssh.exec_command('command with no output')
stdin, stdout, stderr = ssh.exec_command('command with output')
sh_ver = stdout.readlines()

问题是exec_command 导致通道关闭并且无法重用,但我无法打开新通道来执行另一个命令,因为这是一个命令会话最后我需要得到输出。

我也尝试过以这种方式执行命令:

stdin, stdout, stderr = ssh.exec_command('''
command
command
command
''')
output = stdout.readlines()

但是这样,output 是空的。即使它不会,我也需要对output 执行一些检查,然后继续我停止的会话。

那么我需要什么?一种无需关闭或启动新连接即可管理此 ssh 连接并轻松接收命令输出的方法。

提前致谢,美里。 :)

【问题讨论】:

    标签: python-2.7 ssh paramiko cisco cisco-ios


    【解决方案1】:

    我认为你需要的是invoke_shell()。例如:

    ssh = paramiko.SSHClient()
    ... ...
    chan = ssh.invoke_shell() # starts an interactive session
    
    chan.send('command 1\r')
    output = chan.recv()
    
    chan.send('command 2\r')
    output = chan.recv()
    ... ...
    

    Channel 有许多其他方法。详情可参考document

    【讨论】:

      【解决方案2】:

      您需要正确地将命令链接在一起,就像在 shell 脚本中一样:

      stdin, stdout, stderr = ssh.exec_command('''
      command1
      && command2
      && command3
      ''')
      

      【讨论】:

      • 哦,好吧..但正如我所说,是否可以检查输出,然后以这种方式在同一个会话中继续?
      • @MiriAdj:我知道你说过exec_command() 每次会话只能使用一次,但我认为这不是真的。您的意思是要“继续”相同的命令链吗?如果您更具体地了解命令是什么,那将非常有帮助。
      • 是的,它是一个命令链..这些命令是针对 cisco 设备的,所以这些是一些设置,然后我得到一个输出..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2014-12-28
      • 2021-07-10
      • 2012-10-30
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      相关资源
      最近更新 更多