【问题标题】:Read command output in Paramiko without prompts and other shell output在没有提示和其他 shell 输出的情况下读取 Paramiko 中的命令输出
【发布时间】:2022-01-31 15:22:37
【问题描述】:

我正在尝试将特定命令的输出发送到 txt 文件,

file = 'output_from_the_server.txt'

def connect(host):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname=host, port=port, username=username, password=password, look_for_keys=False, allow_agent=False)
    ssh = client.invoke_shell()
    return ssh

def test(server_host):
    print(server_host)
    IP = server_view(server_host)
    print(IP)
    ssh = connect(IP)
    time.sleep(2)
    ssh.send('clear -x && [command]\n')
    time.sleep(3)
    resp = ssh.recv(655353)
    output = resp.decode('ascii').split(',')
    output = ''.join(output)
    ssh.close()

    with open(file, 'w') as f:
        for i in output:
            f.write(i)
    f.close()

该文件包括命令之前的所有输出,即使我尝试使用清除屏幕。

【问题讨论】:

    标签: python shell ssh paramiko


    【解决方案1】:

    这是一个通过 paramiko 执行命令的示例。

    然后将输出发送到文件应该很容易。

    def ssh_command(ip, user, command):
        key = paramiko.RSAKey.from_private_key_file(os.getenv('HOME') + '/.ssh/paramiko')
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(ip, username=user, pkey=key)
        ssh_session = client.get_transport().open_session()
        if ssh_session.active:
            ssh_session.exec_command(command)
            out = []
            r = ssh_session.recv(1024).decode('utf-8')
            while r:
                out.append(r)
                r = ssh_session.recv(1024).decode('utf-8')
    
            return ''.join(out)
        return ''
    
    res = ssh_command('127.0.0.1', 'user', 'cd / ; ls */ | xargs ls')
    for outputin str(res).split('\\n'):
        print(output)
    

    不要忘记使用 ssh-keygen 生成密钥。

    【讨论】:

    • 您可以用更少的代码更可靠地实现相同的目标。看我的回答。
    • 啊是的不知道。谢谢!
    【解决方案2】:

    您正在启动一个 shell,因此很自然地会得到所有在 shell 中会得到的输出,包括所有提示和横幅。

    不要使用 shell 自动执行命令,使用“exec”SSH 通道。

    stdin, stdout, stderr = client.exec_command(command)
    stdout.channel.set_combine_stderr(True)
    output = stdout.readlines()
    

    Paramiko: read from standard output of remotely executed command


    相关问题:
    Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?


    强制性警告:不要单独使用AutoAddPolicy - 这样做会失去对MITM attacks 的保护。如需正确解决方案,请参阅Paramiko "Unknown Server"

    【讨论】:

      猜你喜欢
      • 2011-09-11
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多