【问题标题】:Python2.7: ssh.exec_command not executing any command [duplicate]Python2.7:ssh.exec_command 不执行任何命令 [重复]
【发布时间】:2016-10-27 00:29:33
【问题描述】:

我正在使用paramiko 为远程主机创建一个SSH Channel。但是,当我尝试使用ssh_object.exec_command 执行任何命令时,该命令似乎没有被执行。

此函数创建我的ssh 处理程序:

def ssh_connect(ip,user,pwd):
    '''
    This function will make an ssh connection to the ip using the credentials passed and return the handler
    Args:
        ip: IP Address of the box into which ssh has to be done
        user: User name of the box to which ssh has to be done
        pass: password of the box to which ssh has to be done
    Returns:
        An ssh handler
    '''
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, username=user, password=pwd)  
    return ssh

这就是我使用处理程序的地方:

ssh_obj = ssh_connect(ip, username, password)
folder = "/var/xyz/images/" + build_number
command = "mkdir " + folder
ssh_stdin, ssh_stdout, ssh_stderr = ssh_obj.exec_command(command)

当我转到远程机器时,该文件夹尚未创建。同样,我也尝试读取ls 命令的输出。当我ssh_stdout.read() 时没有响应。

我哪里出错了?

【问题讨论】:

  • 你能检查一下ssh_stderr有没有log吗?
  • @AlekhyaVemavarapu,我该如何检查?
  • 试试 command="mkdir -p " + 文件夹
  • 这似乎也不起作用,@skynyrd。
  • 还有@Alekhya,ssh_stderr 中没有日志

标签: python python-2.7 ssh paramiko


【解决方案1】:

我在使用 paramiko 2.0.2 的 CentOS 7 服务器上遇到了同样的问题。 paramiko github主页上的示例起初对我不起作用:https://github.com/paramiko/paramiko#demo

import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=self.server['host'], username=self.server['username'], password=self.server['password'])
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
    print '... ' + line.strip('\n')
client.close()

在我更新远程系统后,上面的示例开始工作。但不是我编写的代码(类似于 OP 的代码)这提出了我需要在执行后立即读取 stdout 缓冲区的想法。所以我修改了代码来做到这一点并且它有效。根据 OP 的代码,它可能看起来像

ssh_obj = ssh_connect(ip, username, password)
folder = "/var/xyz/images/" + build_number
command = "mkdir " + folder
ssh_stdin, ssh_stdout, ssh_stderr = ssh_obj.exec_command(command)
# Read the buffer right after the execution:
ssh_stdout.read()

有趣的是,稍后(在您关闭客户端之后)读取缓冲区不会给您带来任何好处。

【讨论】:

    【解决方案2】:

    ssh_exec_command 行之后;添加以下条件。

    只有在命令(shell)完全执行后,循环才会退出。

    while int(stdout.channel.recv_exit_status()) != 0: time.sleep(1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 2020-12-08
      • 2018-12-19
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多