import pexpect
PROMPT = ['# ', '>>> ', '> ', '\$ ']
def send_command(child, cmd):
child.sendline(cmd)
child.expect(PROMPT)
print(child.before)
def connect(user, host, password):
ssh_newkey = 'Are you sure you want to continue connecting'
connStr = 'ssh ' + user + '@' + host
child = pexpect.spawn(connStr)
ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:'])
if ret == 0:
print('[-] Error connecting')
return
if ret == 1:
child.sendline('yes')
ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:'])
if ret == 0:
print('[-] Error connecting')
return
child.sendline(password)
child.expect(PROMPT)
return child
def main():
host = '192.168.10.101'
user = 'root'
password = '123456'
child = connect(user, host, password)
send_command(child, 'cat /etc/shadow | grep root')
if __name__ == '__main__':
main()
AttributeError: module 'pexpect' has no attribute 'spawn'
,这是因为不支持windows系统,在linux下运行即可下载python3.7.tgz
解压后进入目录中,需要自己编译python3环境
首先:创建目录
mkdir /usr/local/python3
其次:执行配置
./configure –prefix=/usr/local/python3
这个地方可能会报错,说没有gcc,因为没有安装gcc,所以无法成功创建makefile,这里只需安装一下即可
yum install gcc -y yum install make -y
安装完毕后重新执行上一句后再执行
make & make install
等接受后运行puthon3即可,如果不行,就把python3创建到/usr/bin中
ModuleNotFoundError: No module named '_ctypes'
yum install libffi-devel -y
make install
然后再按照上面的过程,重写编译一下python3就行
其实不用安装,python3中有,只是没有添加到/usr/bin中,自己加一下就行
点击到官网下载pexpect4.6.0
下载后解压
解压后到目录中运行
python ./setup.py install
到这里,文中开头的例子依然无法执行,会报错,进入python3解释器中
导入pexpect,会发现
>>> import pexpect
Traceback (most recent call last):
File "" , line 1, in <module>
File "pexpect/__init__.py", line 75, in <module>
from .pty_spawn import spawn, spawnu
File "pexpect/pty_spawn.py", line 11, in <module>
import ptyprocess
ImportError: No module named ptyprocess
ptyprocess
下载地址
下载后和安装pexpect一样,进行安装