Python3 用pexpect进行ssh交互(附带python3在linux下安装)
linux-dash
A beautiful web dashboard for Linux
项目地址:https://gitcode.com/gh_mirrors/li/linux-dash
免费下载资源
·
用pexpect
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()
window环境下运行不了,会报错AttributeError: module 'pexpect' has no attribute 'spawn'
,这是因为不支持windows系统,在linux下运行即可
安装python3
下载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中
但是这样安装的python3是有缺陷的,会报错
ModuleNotFoundError: No module named '_ctypes'
这是3.7版本的问题,3.7版本需要一个新的包libffi-devel,安装此包之后再次进行编译安装即可
yum install libffi-devel -y
make install
然后再按照上面的过程,重写编译一下python3就行
安装pip3
其实不用安装,python3中有,只是没有添加到/usr/bin中,自己加一下就行
安装pexpect
点击到官网下载pexpect4.6.0
下载后解压
解压后到目录中运行
python ./setup.py install
到这里,文中开头的例子依然无法执行,会报错,进入python3解释器中
导入pexpect,会发现
>>> import pexpect
Traceback (most recent call last):
File "<stdin>", 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
安装ptyprocess
下载后和安装pexpect一样,进行安装
到这里,就完全ok了,可以运行文章开头的示例了
GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e
added ecosystem file for PM2 4 年前
5def40a3
Add host customization support for the NodeJS version 4 年前
更多推荐
已为社区贡献2条内容
所有评论(0)