-
Notifications
You must be signed in to change notification settings - Fork 1
/
pexpect-ssh.py
80 lines (70 loc) · 2.48 KB
/
pexpect-ssh.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 22:09:19 2018
@author: afei
"""
# pip3 install pexpect
# 连接ssh的模块
# expect
import pexpect
import optparse
prompt = ['[p|P]assword:','#', '>>>', '>', '\$'] # 捕获到列表中任意一个元素表示连接成功
# '\$':结束
# ‘#’:命令执行成功,或者是ssh连接成功
def send_command(child, cmd):
# sendline
child.sendline(cmd)
index = child.expect(prompt)
# index 匹配到的索引值
if prompt[index] == prompt[-1]:
print('[-]Connect Closed')
print(child.before.decode())
# child.before在匹配完成之后 可以拿出来匹配之前的东西
def connect(user, host, password):
# ssh连接的各种状态:
# Are you sure you want to continue connecting (yes/no)?
# [email protected]'s password:
# Permission denied, please try again.
# Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
# Connection closeed by 192.168.2.222
# ssh: connect to host 192.168.2.22 port 22: No route to host
# ssh: Could not resolve hostname 192.168.2.222222: Name or service not known
f_con = 'Are you sure you want to continue connecting'
connstr = 'ssh' + user + '@' + host
# ssh [email protected]
child = pexpect.spawn(connstr,timeout=3)
#spawn spawn spawn spawn spawn
ret = child.expect([pexpect.TIMEOUT,f_con,'[p|P]assword]:'])
if ret == 0:
print('[-]Time out',host)
return
if ret == 1:
child.sendline('yes')
ret = child.expect([pexpect.TIMEOUT,'[p|P]assword]:'])
if ret == 0:
print('[-]Time out',host)
return
child.sendline(password) # 发送密码
index = child.expect(prompt) # 进行捕获
if index == 0:
child.sendline(password)
index += 1
res = child.expect(prompt)
if prompt[res] == prompt[-1] or prompt[res] == '[p|P]assword]:':
print('*******************')
print('[+]Connection Failed!!!)
return
print('[+]Connection Success!!!')
return child
parser = optparse.OptionParser()
parser.add_option('-H',dest='host',type='string')
parser.add_option('-u',dest='user',type='string')
parser.add_option('-p',dest='passwd',type='string')
options,agrs = parser.parse_args()
host = options.host
user = options.user
passwd = options.passwd
connect(user, host, passwd)
cmd = input('Shell you wanna type:')
send_command(child,cmd)
### windows中无法运行pexpect模块,但在linux可以。