Oct
31
pexpect 使用范例
在shell里头,有些程序(比如ssh)的交互是从pty中读取的数据,直接的重定向无法解决,因此需要用到expect这种东西。不过这货的编译比较麻烦,各种依赖。幸好有个pexpect是纯python的,存档留个记录。
如果密码错误的话,输出
如果正确,则输出
转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php 。
#!/usr/bin/python
import sys
import pexpect
password = 'password'
expect_list = ['(yes/no)', 'password:']
p = pexpect.spawn('ssh username@localhost ls')
try:
while True:
idx = p.expect(expect_list)
print p.before + expect_list[idx],
if idx == 0:
print "yes"
p.sendline('yes')
elif idx == 1:
print password
p.sendline(password)
except pexpect.TIMEOUT:
print >>sys.stderr, 'timeout'
except pexpect.EOF:
print p.before
import sys
import pexpect
password = 'password'
expect_list = ['(yes/no)', 'password:']
p = pexpect.spawn('ssh username@localhost ls')
try:
while True:
idx = p.expect(expect_list)
print p.before + expect_list[idx],
if idx == 0:
print "yes"
p.sendline('yes')
elif idx == 1:
print password
p.sendline(password)
except pexpect.TIMEOUT:
print >>sys.stderr, 'timeout'
except pexpect.EOF:
print p.before
如果密码错误的话,输出
引用
The authenticity of host 'localhost (127.0.0.1)' can't be established.
RSA key fingerprint is fe:00:00::00:00:00:00:00:00:00:00:00:00:00:00.
Are you sure you want to continue connecting ((yes/no) yes
)? yes
Warning: Permanently added 'localhost' (RSA) to the list of known hosts.
username@localhost's password: password
Permission denied, please try again.
username@localhost's password: password
Permission denied, please try again.
username@localhost's password: password
Permission denied (publickey,gssapi-with-mic,password).
RSA key fingerprint is fe:00:00::00:00:00:00:00:00:00:00:00:00:00:00.
Are you sure you want to continue connecting ((yes/no) yes
)? yes
Warning: Permanently added 'localhost' (RSA) to the list of known hosts.
username@localhost's password: password
Permission denied, please try again.
username@localhost's password: password
Permission denied, please try again.
username@localhost's password: password
Permission denied (publickey,gssapi-with-mic,password).
如果正确,则输出
引用
username@localhost's password: password
a
b
bin
code
a
b
bin
code
欢迎扫码关注:
转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php 。