如何使用Paramiko执行多行命令并只读取它们的输出。

3

如何使用Paramiko执行多个命令并将输出读取回我的Python脚本?

理论上,这个问题在这里已经有了答案:How do you execute multiple commands in a single session in Paramiko? (Python),但我认为那个答案是不正确的。

问题在于,当你读取stdout时,它会读取终端的整个内容,包括你在终端中“输入”的程序。

只需尝试一下(这基本上是从上面的线程中复制粘贴的):

import paramiko  
machine = "you machine ip"
username = "you username"
password = "password"
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(machine, username = username, password = password)
channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')
stdin.write('''
cd tmp
ls
exit
''')
print stdout.read()
stdout.close()
stdin.close()
client.close()

我的问题是,如何执行多个命令并仅读取这些命令的输出,而不是我“输入”的内容和输出?

非常感谢您的帮助和时间。

3个回答

2
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target_host = 'x.x.x.x'
target_port = 22  
target_port = 22
pwd = ':)'
un = 'root'
ssh.connect( hostname = target_host , username = un, password =pwd)
#Now exeute multiple commands seperated by semicolon
stdin, stdout, stderr = ssh.exec_command('cd mydir;ls')
print stdout.readlines()

创建SSHClient对象,然后调用“connect()”连接本地SSH服务器。设置主机密钥策略需要一次对ssh客户端对象的方法调用(“set_missing_host_key_policy()”),它设置了您想要管理入站主机密钥的方式,或者您可以使用paramiko.AutoAddPolicy()”,它将自动接受未知密钥(不安全)。下一步我们设置主机名、密码、目标主机和目标端口(22 ssh端口)。我们使用ssh客户端对象调用connect方法,然后调用exec_command并传递命令并将命令输出存储在stdout中,最后使用stdout.readlines()读取输出。 - SlickTester

0

你看到你输入的命令是因为 shell 回显它们。你可以通过运行以下命令来关闭回显:

stty -echo

在你的其他命令之前。

另一种方法是不调用交互式 shell,而是直接运行命令,除非你特别需要交互式 shell。例如,你可以这样说:

client.exec_command('/bin/sh -c "cd /tmp && ls")

如果您想要一个没有pty的shell,可以尝试使用:
client.exec_command('/bin/sh')

我认为那也会抑制回声。


0

这应该可以工作:

# Explicitly provide key, ip address and username
from paramiko import SSHClient, AutoAddPolicy

result = []

def ssh_conn():
    client = SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(AutoAddPolicy())

    client.connect('<host_IP_address>', username='<your_host_username>', key_filename='<private_key_location>')

    stdin, stdout, stderr = client.exec_command('ls -la')

    for each_line in stdout:
        result.append(each_line.strip('\n'))
    
    client.close()

ssh_conn()


for each_line in result:
    print(each_line.strip())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接