Python脚本无法正确输出SSH命令

时间:2016-10-28 21:48:51

标签: python

我的代码中有这个功能 -

def name():
     print("Connecting to  server.")
     host = '111.222.232.129'
     client.connect(host, username=username, pkey=mykey)
     for item in tenants:
          stdin, stdout, stderr = client.exec_command("""sudo -u apache grep -i "my_text" /var/www/html/wwwroot/names." + ''.join(item) + "website/myfile.txt | awk -F "'" '{ print $4}'""")

          print stdout

循环来自的变量是 -

tenants = [ ['Kyle'],
          ['Greg'],
          ['Giles'],
          ['George'],
          ['Sebastien'],
          ['Ricardo'],
          ['Rocky'],
          ['Cartman'],
          ['Kenny'],
          ['Bobby'],
          ['Tim'],
          ['Chris'] ]

运行此代码时,我在调用name函数时得到的输出是 -

Connecting to server.
<bound method ChannelFile.read of <paramiko.ChannelFile from <paramiko.Channel 1 (open) window=2097152 -> <paramiko.Transport at 0x941290L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>>
<bound method ChannelFile.read of <paramiko.ChannelFile from <paramiko.Channel 2 (open) window=2097152 -> <paramiko.Transport at 0x941290L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>>
<bound method ChannelFile.read of <paramiko.ChannelFile from <paramiko.Channel 3 (open) window=2097152 -> <paramiko.Transport at 0x941290L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>>

如果我制作了打印语句print stdout.read(),我会得到一些空行。

我在bash中运行此命令时的输出是我想要的输出,因此我运行的实际命令有效并返回正确的输出。

如何显示正确的字符串?如何从stdout获取bash命令的预期输出?

感谢。

1 个答案:

答案 0 :(得分:-1)

command = client.exec_command("""sudo -u apache grep -i "my_text" /var/www/html/wwwroot/names." + ''.join(item) + "website/myfile.txt | awk -F "'" '{ print $4}'""")

for c in command:
    print c

那应该打印实际结果。基本上循环响应。