Python模块:paramiko

时间:2023-03-08 19:08:23

paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。

1、下载安装

Windows:pip3 install paramiko

Linux:

# pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto

# 下载安装 pycrypto
wget http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/pycrypto-2.6.tar.gz
tar -xvf pycrypto-2.6.1.tar.gz
cd pycrypto-2.6.1
python setup.py build
python setup.py install # 进入python环境,导入Crypto检查是否安装成功
from Crypto.Cipher import AES # 下载安装 paramiko
目前新的版本,官网在此:
https://github.com/paramiko/paramiko
unzip paramiko-master.zip
cd paramiko-master
python setup.py build
python setup.py install
centos7 Python3 可以直接pip3 install paramiko 我用的这种方法
# 进入python环境,导入paramiko检查是否安装成功
 [root@greg02 ~]# pip3 install paramiko
Collecting paramiko
Downloading paramiko-2.4.0-py2.py3-none-any.whl (192kB)
100% |████████████████████████████████| 194kB 65kB/s
Collecting bcrypt>=3.1.3 (from paramiko)
Downloading bcrypt-3.1.4-cp36-cp36m-manylinux1_x86_64.whl (54kB)
100% |████████████████████████████████| 61kB 99kB/s
Collecting cryptography>=1.5 (from paramiko)
Downloading cryptography-2.1.3-cp36-cp36m-manylinux1_x86_64.whl (2.2MB)
100% |████████████████████████████████| 2.2MB 95kB/s
Collecting pyasn1>=0.1.7 (from paramiko)
Downloading pyasn1-0.3.7-py2.py3-none-any.whl (63kB)
100% |████████████████████████████████| 71kB 203kB/s
Collecting pynacl>=1.0.1 (from paramiko)
Downloading PyNaCl-1.2.0-cp36-cp36m-manylinux1_x86_64.whl (692kB)
100% |████████████████████████████████| 696kB 91kB/s
Collecting six>=1.4.1 (from bcrypt>=3.1.3->paramiko)
Downloading six-1.11.0-py2.py3-none-any.whl
Collecting cffi>=1.1 (from bcrypt>=3.1.3->paramiko)
Downloading cffi-1.11.2-cp36-cp36m-manylinux1_x86_64.whl (419kB)
100% |████████████████████████████████| 430kB 339kB/s
Collecting idna>=2.1 (from cryptography>=1.5->paramiko)
Downloading idna-2.6-py2.py3-none-any.whl (56kB)
100% |████████████████████████████████| 61kB 388kB/s
Collecting asn1crypto>=0.21.0 (from cryptography>=1.5->paramiko)
Downloading asn1crypto-0.23.0-py2.py3-none-any.whl (99kB)
100% |████████████████████████████████| 102kB 416kB/s
Collecting pycparser (from cffi>=1.1->bcrypt>=3.1.3->paramiko)
Downloading pycparser-2.18.tar.gz (245kB)
100% |████████████████████████████████| 256kB 387kB/s
Installing collected packages: six, pycparser, cffi, bcrypt, idna, asn1crypto, cryptography, pyasn1, pynacl, paramiko
Running setup.py install for pycparser ... done
Successfully installed asn1crypto-0.23.0 bcrypt-3.1.4 cffi-1.11.2 cryptography-2.1.3 idna-2.6 paramiko-2.4.0 pyasn1-0.3.7 pycparser-2.18 pynacl-1.2.0 six-1.11.0
[root@greg02 ~]# python3
Python 3.6.2 (default, Nov 15 2017, 04:14:48)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>>

安装记录

Python模块:paramiko

2.远程连接Linux(centos7)并打印命令结果

import paramiko

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect('192.168.179.130', 22, 'root', '') # 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
print(stdout.read()) # 关闭连接
ssh.close()

3. 通过公钥连接,前提是两台Linux可以互相连接

比如在Linux1(192.168.179.131)上配置公钥私钥,通过ssh 192.168.179.130无需输入密码可以连接Linux2

[root@greg02 ~]# ssh 192.168.179.130
Last login: Wed Nov 15 19:31:19 2017 from 192.168.179.131
[root@greg01 ~]#
[root@greg01 ~]#exit
logout
Connection to 192.168.179.130 closed.
import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect('192.168.179.130', 22, 'root', '123456',key=private_key) # 执行命令
stdin, stdout, stderr = ssh.exec_command('df') # 获取命令结果
result = stdout.read() # 关闭连接
ssh.close()

4.上传或下载文件

import os,sys
import paramiko t = paramiko.Transport(('192.168.179.130',22))
t.connect(username='root',password='greg311') sftp = paramiko.SFTPClient.from_transport(t) sftp.get('/root/test.py','d:/test.py')
sftp.put('d:/test.jpg','/root/test.jpg')
t.close()

5.通过密钥上传或下载文件

import paramiko

pravie_key_path = '/root/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path) t = paramiko.Transport(('192.168.179.130',22))
t.connect(username='wupeiqi',pkey=key) sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test3.py','/tmp/test3.py')
sftp.get('/tmp/test4.py','/tmp/test4.py')
t.close()

6.python3 paramiko-master/demos/demo.py

[root@greg02 demos]#python3 demo.py
Hostname: 192.168.179.131
*** WARNING: Unknown host key!
Username [root]: root
Auth by (p)assword, (r)sa key, or (d)ss key? [p] p
Password for root@192.168.179.131:
*** Here we go! Last login: Wed Nov 15 19:09:05 2017 from 192.168.179.1
[root@greg01 ~]# ls
123.txt anaconda-ks.cfg index.html para2.py rsync
[root@greg01 ~]# exit
logout *** EOF
[root@greg02 demos]#vim demo.py

7.interactive捕获命令并记录

 import socket
import sys
import time
from paramiko.py3compat import u # windows does not have termios...
try:
import termios
import tty
has_termios = True
except ImportError:
has_termios = False def interactive_shell(chan):
if has_termios:
posix_shell(chan)
else:
windows_shell(chan) def posix_shell(chan):
import select oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
cmd = []
f = open('ssh_test.log','w')
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = u(chan.recv(1024))
if len(x) == 0:
sys.stdout.write('\r\n*** EOF\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
if x == '\r':
print('input>',''.join(cmd))
log = "%s %s\n" %(time.strftime("%Y-%m-%d %X", time.gmtime()), ''.join(cmd))
print(log)
f.write(log)
cmd = []
else:
cmd.append(x)
chan.send(x) finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
f.close() # thanks to Mike Looijmans for this code
def windows_shell(chan): print("window chan",chan.host_to_user_obj)
print("window chan",chan.crazyeye_account)
import threading sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n") def writeall(sock):
while True:
data = sock.recv(256)
if not data:
sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
sys.stdout.flush()
break
sys.stdout.write(data)
sys.stdout.flush() writer = threading.Thread(target=writeall, args=(chan,))
writer.start() try:
while True:
d = sys.stdin.read(1)
if not d:
break
chan.send(d)
except EOFError:
# user hit ^Z or F6
pass

运行:

[root@greg02 demos]#cat ssh_test.log
2017-11-15 12:33:18 ls
2017-11-15 12:33:32 cd /pa pa mi
2017-11-15 12:33:33 ls
2017-11-15 12:33:40 exit