【问题标题】:Perform unix operations after connecting to remote host using ssh使用 ssh 连接到远程主机后执行 unix 操作
【发布时间】:2018-02-07 05:39:09
【问题描述】:

使用 paramiko 连接远程主机。如何跨目录移动并执行 unix 操作?下面的示例代码

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote ip', username='username', password='password')
ftp = ssh.open_sftp()
ssh.exec_command('cd /folder1/folder2')

我如何执行诸如列出目录中的文件、检查当前工作目录和执行其他 unix 命令之类的操作?

【问题讨论】:

    标签: python paramiko


    【解决方案1】:

    这样(ls 命令的示例):

    import paramiko
    import sys
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('x.x.x.x', port=22, username='user', password='pass')
    stdin, stdout, stderr = ssh.exec_command('ls')
    
    # Wait for the command to terminate
    while not stdout.channel.exit_status_ready():
        # Only print data if there is data to read in the channel
        if stdout.channel.recv_ready():
            rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
            if len(rl) > 0:
                # Print data from stdout
                print stdout.channel.recv(1024),
    
    
    
    ssh.close()
    

    【讨论】:

    • 我试过这个,但是当我打印标准输出时它没有列出目录中的所有文件。我得到这样的输出 >>
    • 不知道。在这里有效。查看 Paramiko 文档(命令 SSHClient):docs.paramiko.org/en/2.2/api/client.html
    • 我已经编辑了我的代码,添加了一个等待循环,让 stdout 在打印前终止。
    • 如果你修正了,你介意检查答案附近的绿色箭头吗?如果没有,请发布输出错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2020-03-20
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多