0
我試圖自動化互動SSH電話(見注1)如下:子:stdout和stderror似乎互換或混合
SSHBINARY = '/usr/bin/ssh'
ASKPASS = '/home/mz0/checkHost/askpass.py'
def sshcmd(host,port,user,password,cmd):
env0 = {'SSH_ASKPASS': ASKPASS, 'DISPLAY':':9999'}
ssh = subprocess.Popen([SSHBINARY,"-T","-p %d" % port,
"-oStrictHostKeyChecking=no", "-oUserKnownHostsFile=/dev/null",
"%[email protected]%s" % (user,host), cmd],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env0,
preexec_fn=os.setsid
)
error = ssh.stderr.readlines()
result = ssh.stdout.readlines()
return error,result
host = 'localhost'
port = 22
user = 'try1'
password = '1try' # unused, hardcoded in ASKPASS
cmd = 'ls'
result1, error1 = sshcmd(host,port,user,password,cmd)
if result1 : print "OUT: %s" % result1
if error1 : print "ERR: %s" % error1
原來我在做一些愚蠢的事,因爲我得到這個:
OUT: ["Warning: Permanently added 'localhost' (RSA) to the list of known hosts.\r\n"]
ERR: ['['Desktop\n', ..., 'Videos\n']']
很明顯,stdout和stderr被交換(注2)。你能指點我的錯誤嗎?
注意1:我很清楚無密碼的ssh,忽略主機密鑰等的危險,以及討厭自動化交互式ssh的請求與您一樣多。
注2:運行在外殼相同的命令證實,輸出和錯誤在我的代碼
ssh -o 'UserKnownHostsFile /dev/null' -o 'StrictHostKeyChecking no' \
[email protected] ls > ssh-out 2> ssh-error
你的命令應該失敗 - '「-p%d」%port'應該是兩個參數:'「-p」,str(port)'。如果ssh在stdout上生成足夠的輸出來填充OS管道緩衝區,那麼它會死鎖。使用'ssh.communicate()'而不是readlines()來避免它。 – jfs