python pexpect 无法执行 service 命令
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
def ssh_cmd(ip, passwd, cmd):
ret = -1
ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))
try:
i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=15)
if i == 0 :
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password: ')
ssh.sendline(passwd)
ssh.sendline(cmd)
r = ssh.read()
print '------ this is : ----------------------------'
print r,
print '------ has been excuted ------------------------'
ret = 0
except pexpect.EOF:
print "EOF"
ssh.close()
ret = -1
except pexpect.TIMEOUT:
print "TIMEOUT"
ssh.close()
ret = -2
return ret
如果后边执行
ssh_cmd('192.168.9.11','$password','service tomcat stop')
则 没有 任何相应 最终timeout ,没有 执行命令和 没有反馈。
如果后边执行
ssh_cmd('192.168.9.11','$password',' mount -l')
可以 通过print r 正常 执行,而且反馈正常