来自stderr的错误 - 如何解决?

时间:2013-04-01 18:14:51

标签: python ssh stderr

我有一个Python程序(下面),当我运行它时,我收到以下错误:

% python SSH_Prog.py
About to connect...
stderr:  ["bash: -c: line 0: unexpected EOF while looking for matching `''\n", 'bash: -c: line 1: syntax error: unexpected end of file\n']
pwd:  []
stderr:  ['watch: no process found\n']
pwd:  []
^CTraceback (most recent call last):
  File "SSH_Prog.py", line 32, in <module>
    time.sleep(3)
KeyboardInterrupt

我认为这可能与转义序列有关,并且&#34; \ n&#34;来自stdin的角色,但我缺乏处理它的经验。

这是程序:

import os
import sys
import time
import paramiko
#from ssh import SSHClient

# Define remote machine
host="<ip>"
user="<usrnm>"
passw="<passw>"
client = paramiko.SSHClient()
#client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Try SSH connection, catch exception
#if not
print('About to connect...') 

client.connect(host, username=user, password=passw)
# ForLoop to iterate through the interactions
for x in range(10):
    xx = str(x)
    # Commands to execute on local machine
    f = os.popen3('tshark -i eth0 -f snmp -F pcapng -w ~/Desktop/traf_logs/n'+(xx))
    # commands to execute on remote machine
    stdin, stdout, stderr = client.exec_command("watch -n 0.1 'ps -p $(pgrep -d"," -x snmpd) -o rss= | awk '\''{ i += $1 } END { print i }'\'' >> ~/Desktop/mem_logs/mem_"+(xx)+";")        
    print "stderr: ", stderr.readlines()
    print "pwd: ", stdout.readlines()

    g = os.popen3('snmpget -v 2c -c communitystring <ip> sysContact.0')     
    time.sleep(3)

    stdin, stdout, stderr = client.exec_command('killall watch;')          
    print "stderr: ", stderr.readlines()
    print "pwd: ", stdout.readlines()

    ff = os.popen3('killall tshark')        
# terminate connection
client.close()
exit(0)

你有什么想法解决它吗?

问候。

1 个答案:

答案 0 :(得分:1)

您的第一个exec_command看起来像这样:

stdin, stdout, stderr = client.exec_command("watch -n 0.1 'ps -p $(pgrep -d"," -x snmpd) -o rss= | awk '\''{ i += $1 } END { print i }'\'' >> ~/Desktop/mem_logs/mem_"+(xx)+";")        

换句话说,第一个参数是:

"watch -n 0.1 'ps -p $(pgrep -d"

你的第二个论点是:

" -x snmpd) -o rss= | awk '\''{ i += $1 } END { print i }'\'' >> ~/Desktop/mem_logs/mem_"+(xx)+";"

如果您在终端中启动bash并输入第一个参数(不带引号),后跟换行符和^ D,它会告诉您:

> -bash: unexpected EOF while looking for matching `''
-bash: syntax error: unexpected end of file

这正是你从Paramiko那里得到的。

第二个错误只是killall,告诉您没有名为watch的进程,因为您的第一个命令从未启动过。

如果你只是用空格替换",",那就解决了这个问题......但不知道为什么你认为你想要","那里,我不确定它会做什么你真的打算这样做。

我也不确定'\''应该做什么。你为什么要对awk的参数进行三重引用,或者为什么你做的事情如此复杂呢?它应该等同于{ print $1 },或者为什么你明确要求{{1}多列只是使用ps来挑出第一个,或者......