Pexpect 实例: 登陆到远程机器执行命令
时间:2010-06-04 来源:oychw
#!/usr/bin/env python
#gtalk: xurongzhong#gmail.com
import pxssh
ips = ["10.144.18.245","10.144.18.242"]
for ip in ips:
print ip
s = pxssh.pxssh()
s.login(ip, "user", "passwd",port=36000)
s.sendline('ls') # run a command
s.prompt() # match the prompt
print s.before # print everything before the propt.
s.sendline ("uptime") # run a command
s.prompt() # match the prompt
print s.before # print everything before the propt.
s.logout()
执行结果:
# ./test.py
10.144.18.245
ls
Documents bin isu.tar.gz public_html
uptime
10:59am up 42 days 23:25, 1 user, load average: 11.08, 7.84, 4.42
10.144.18.242
ls
Documents bin isu.tar.gz public_html
uptime
11:00am up 42 days 23:26, 1 user, load average: 3.50, 9.75, 9.89
注意点:
如果报错:
#gtalk: xurongzhong#gmail.com
import pxssh
ips = ["10.144.18.245","10.144.18.242"]
for ip in ips:
print ip
s = pxssh.pxssh()
s.login(ip, "user", "passwd",port=36000)
s.sendline('ls') # run a command
s.prompt() # match the prompt
print s.before # print everything before the propt.
s.sendline ("uptime") # run a command
s.prompt() # match the prompt
print s.before # print everything before the propt.
s.logout()
执行结果:
# ./test.py
10.144.18.245
ls
Documents bin isu.tar.gz public_html
uptime
10:59am up 42 days 23:25, 1 user, load average: 11.08, 7.84, 4.42
10.144.18.242
ls
Documents bin isu.tar.gz public_html
uptime
11:00am up 42 days 23:26, 1 user, load average: 3.50, 9.75, 9.89
注意点:
如果报错:
pexpect .TIMEOUT: Timeout exceeded in read_nonblocking()
修改site-packages/pxssh.py
在def synch_original_prompt (self):方法下第一个self.read_nonblocking(size=10000,timeout=1) 前面增加两行代码
self.sendline()
time.sleep(0.1)
使用pxssh的速度好像一直比直接使用pexpect要慢,这方面还有待探索!
相关阅读 更多 +