【问题标题】:Paramiko can't get output for grep commandParamiko 无法获得 grep 命令的输出
【发布时间】:2016-06-20 11:35:57
【问题描述】:

我正在使用paramiko 库。

使用shell = ssh.invoke_shell()shell.send()

我发送的命令是cmd = """grep -i "Lost LLUS websocket" /var/log/debesys/cme.log\n"""

但我没有得到输出。

我正在使用shell.receive 获取输出,但我总是空白。我已经手动测试了该命令,它工作正常。有人知道如何获取输出吗?

【问题讨论】:

  • 您是否检查了 stderr 的错误和退出状态?
  • 您的意思是使用shell.recv(bytes) 来获取输出吗?如果你运行一些通用命令比如ls,你能得到结果吗?
  • 你能发布你的实际代码吗?另外,您是否考虑过使用 exec_command() 代替?

标签: python linux paramiko


【解决方案1】:

我不确定这是否完全按照您想要的方式工作,但只是离开问题标题,如果您想发送 grep 命令本身,我会这样做:

def run_cmd(sshClient, command):
    channel = sshClient.get_transport().open_session()
    channel.get_pty()
    channel.exec_command(command)
    out = channel.makefile().read()
    err = channel.makefile_stderr().read()
    returncode = channel.recv_exit_status()
    channel.close()                       # channel is closed, but not the client
    return out, err, returncode

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, username = user, password = pw)
out, err, rc = run_cmd(client, 'grep -i "Lost LLUS websocket" /var/log/debesys/cme.log')
# Do whatever with the output
# Run any other commands
client.close()

当然,还有许多其他选择。您可以将文件 scp 到本地计算机,在 python 中打开它,然后搜索它。您甚至可以使用 ssh 调用对文件进行分类,并在输出中使用 python 搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-26
    • 2012-06-29
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多