paramiko是基于Python实现的SSH2远程安全连接,支持认证及密钥方式。可以实现远程命令执行、文件传输、中间SSH代理等功能,相对于Pexpect,封装的层次更高,更贴近SSH协议的功能 。
需要安装一下依赖
Collecting paramiko Downloading paramiko-2.11.0-py2.py3-none-any.whl (212 kB) |████████████████████████████████| 212 kB 76 kB/s Collecting bcrypt>=3.1.3 Downloading bcrypt-4.0.1-cp36-abi3-win_amd64.whl (152 kB) |████████████████████████████████| 152 kB 19 kB/s Collecting pynacl>=1.0.1 Downloading PyNaCl-1.5.0-cp36-abi3-win_amd64.whl (212 kB) |████████████████████████████████| 212 kB 24 kB/s Collecting cryptography>=2.5 Downloading cryptography-38.0.1-cp36-abi3-win_amd64.whl (2.4 MB) |████████████████████████████████| 2.4 MB 15 kB/s Collecting six Downloading six-1.16.0-py2.py3-none-any.whl (11 kB) Collecting cffi>=1.12 Downloading cffi-1.15.1-cp39-cp39-win_amd64.whl (179 kB) |████████████████████████████████| 179 kB 18 kB/s Collecting pycparser Downloading pycparser-2.21-py2.py3-none-any.whl (118 kB) |████████████████████████████████| 118 kB 19 kB/s Installing collected packages: pycparser, cffi, six, pynacl, cryptography, bcrypt, paramiko Successfully installed bcrypt-4.0.1 cffi-1.15.1 cryptography-38.0.1 paramiko-2.11.0 pycparser-2.21 pynacl-1.5.0 six-1.16.0
代码如下
importparamikoimportsysip="121.36.55.115"port=22username="root"password="Jzbank@315"#cmd="ls"cmd1="useradd -m ly"cmd2="echo \"ly:xiucai315\"|chpasswd "ssh_client=paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy) try: ssh_client.connect(hostname=ip,username=username,password=password) exceptExceptionase: print('服务器%s连接失败'%ip) print(e) sys.exit() stdin,stdout,stderr=ssh_client.exec_command(cmd1) stdin1,stdout1,stderr1=ssh_client.exec_command(cmd2) #print("根目录文件列表:")print(stdout.read().decode("utf-8")) print(stdout1.read().decode("utf-8")) ssh_client.close()