pexpect的python输出
请检查我上面的python代码 当我执行: python3 brutekey-ssh.py-H 127.0.0.1-u root-d dsa/1024/pexpect的python输出,python,pexpect,Python,Pexpect,请检查我上面的python代码 当我执行: python3 brutekey-ssh.py-H 127.0.0.1-u root-d dsa/1024/ def connect(user,host,keyfile,release): global Stop global Fails try: perm_denied = 'Permission denied' ssh_newkey = 'Are you sure you w
def connect(user,host,keyfile,release):
global Stop
global Fails
try:
perm_denied = 'Permission denied'
ssh_newkey = 'Are you sure you want to continue'
conn_closed = 'Connection closed by remote host'
opt = ' -o PasswordAuthentication=no'
connStr= 'ssh ' + user + '@' + host + ' -i ' +keyfile + opt
child = pexpect.spawn(connStr)
ret=child.expect([pexpect.TIMEOUT,perm_denied,ssh_newkey,conn_closed,'$','#'])
print(child.before)
if ret== 2:
print('[[-] Adding Host to !/.ssh/known_hosts')
child.sendline('yes')
elif ret ==3:
print('[-] Connection Closed by Remote Host')
Fails += 1
elif ret > 3:
print('[+] Success.' + str(keyfile)+ ' ' + str(ret))
Stop = True
finally:
if release:
connection_lock.release()**
我的问题如下:
ret>3
,为什么child.expect的精确输出
*\$
而不是$
?$
是否仅与输出中的确切$
匹配1:即使它被拒绝了权限,它仍然符合ret>3为什么?
回答:可能是因为
perm_denied
案例的输出包含一个bash字符(“#”和“$”),所以打印child.before
的值,或者在自动化之前手动确定发生了什么。如果它与任何内容都不匹配并导致超时,则应返回0。它返回0而不是引发异常,因为您将pexpect.TIMEOUT
添加到列表中
2:如何检查child.expect的准确输出?ans:
child.expect
返回传递给它的列表中项目的索引(int)。因此,在您的例子中,您通过了[peexpect.TIMEOUT、perm\u denied、ssh\u newkey、conn\u closed、“$”、“#”]
,。expect
将返回后端正则表达式从左到右首先匹配的的索引。它的确切值在ret
变量中
3:我是否需要使用。*\$而不是$?“$”是否仅与输出中的精确$匹配?ans:是的,它足以匹配bash提示符。它们可能会中断的唯一情况是,您孩子的某些内容从某个函数打印出一个
字符
pexpect
很好,请阅读这里的示例,应该有很多。您在perm_denied中给出了什么字符串?在child.before
之后添加print
的值ret=child.expect([pexpect.TIMEOUT,perm_denied,ssh_newkey,conn_closed,“$”,“#])
这样我们就可以知道问题的确切原因。呃,您想做什么?如果必须将密码/用户名传递给需要在命令行上输入的阻塞进程,则通常需要expect
。不过,您使用的是一个密钥进行ssh加密,因此不需要这样做……此外,通常进程返回的0
代码意味着在基于Unix的系统上成功。返回大于3的代码可能意味着任何事情……但不是成功。expect不返回流程代码。它返回indexI edite我的原始帖子:add print(child.before)并打印ret变量。即使child.before是“”,ret是4…………我想检查ssh登录是否成功手动测试的确切提示是:sshroot@127.0.0.1-i dsa/1024/1F09490E311786EC22FF32715CA06E9-1279-o PasswordAuthentication=未拒绝任何权限(公钥、密码)。
[-] Testing keyfile dsa/1024/a31b082ec6434d65c2adf76862b9aca7-30343
[-] Testing keyfile dsa/1024/fb80119b7615bbeb96cb7d2f55b7533d-10375
b''
[+] Success.dsa/1024/1f09490e311786ec22ff32715ca106e9-1279 4
[*] Exiting:Key Found
b''
[+] Success.dsa/1024/b23696eee5b31ed916002d3ec2ddb5f6-18108 4
b''
[+] Success.dsa/1024/a31b082ec6434d65c2adf76862b9aca7-30343 4