编程语言
首页 > 编程语言> > python模块之paramiko

python模块之paramiko

作者:互联网

很多运维人员平时进行维护linux/unix主机时候,无非通过ssh到相应主机操作,那么一旦主机有成千上百台,那该如何应对,这时候我们需要批处理工具,基于python的工具有ansible、salt,而ansible的核心则是基于paramiko。

 

 

安装:

pip install paramiko或 easy_install paramiko

核心组件:

SSHclient类
方法:

connect():远程ssh连接并作校验

参数:

 

exec_command():用于远程执行命令,该命令的输入与输出流为标准输入、标出输出、标准错误输出

参数:

 

load_system_host_key():装载系统公钥,默认为~/.ssh/known_hosts

参数:

 

set_missing_host_key_policy():设置连接的远程主机没有本地主机密钥或HostKeys对象时的策略,目前支持三种,也就是参数只有三个。

参数:

  用法:
  set_missing_host_key_policy(paramiko.AutoAddPolicy())

SFTPClient类

SFTPCLient作为一个sftp的客户端对象,根据ssh传输协议的sftp会话,实现远程文件操作,如上传、下载。

方法:

 

 

 

使用:

1.执行远程命令

1)用户名,密码

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
#Author:wd
import paramiko
host='10.0.0.241'
username='root'
passwd='1234qwer'
ssh=paramiko.SSHClient()#创建SSH对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())#设置自动添加known_host
ssh.connect(hostname=host,username=username,password=passwd,)#连接主机
paramiko.util.log_to_file('tran.log')#设置登陆数据传输日志
stdin,stdout,stderr=ssh.exec_command('ifconfig',timeout=10)#执行命令设置超时时间
stdout,stderr=stdout.read(),stderr.read()
res=stdout if stdout else stderr
print(res.decode())ssh.close()#关闭连接

 

2)使用公钥

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
#Author:wd
host='172.16.11.35'
username='root'

import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())#设置自动添加known_hosts,一定要在connection之前
ssh.connect(username=username,hostname=host,pkey=paramiko.RSAKey.from_private_key_file('/Users/fangchaoliu/.ssh/id_rsa'))
stdin,stdout,stderr=ssh.exec_command('ifconfig')
stdout,stderr=stdout.read(),stderr.read()
res=stdout if stdout else stderr
print(res.decode())

 

3)使用SSHClient封装transport

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
#Author:wd
host=('172.16.11.35',22)
user='root'
passwd='1234qwer'
import paramiko
tran=paramiko.Transport(host)#host是一个tuple,分别是主机和port
tran.connect(username=user,password=passwd)
ssh=paramiko.SSHClient()
ssh._transport=tran
stdin,stdout,stderr=ssh.exec_command('df -h')
stdout,stderr=stdout.read(),stderr.read()
res=stdout if stdout else stderr
print(res.decode())tran.close()

密钥字符串:

import paramiko
from io import StringIO

key_str = """-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAq7gLsqYArAFco02/55IgNg0r7NXOtEM3qXpb/dabJ5Uyky/8
NEHhFiQ7deHIRIuTW5Zb0kD6h6EBbVlUMBmwJrC2oSzySLU1w+ZNfH0PE6W6fans
H80whhuc/YgP+fjiO+VR/gFcqib8Rll5UfYzf5H8uuOnDeIXGCVgyHQSmt8if1+e
7hn1MVO1Lrm9Fco8ABI7dyv8/ZEwoSfh2C9rGYgA58LT1FkBRkOePbHD43xNfAYC
tfLvz6LErMnwdOW4sNMEWWAWv1fsTB35PAm5CazfKzmam9n5IQXhmUNcNvmaZtvP
c4f4g59mdsaWNtNaY96UjOfx83Om86gmdkKcnwIDAQABAoIBAQCnDBGFJuv8aA7A
ZkBLe+GN815JtOyye7lIS1n2I7En3oImoUWNaJEYwwJ8+LmjxMwDCtAkR0XwbvY+
c+nsKPEtkjb3sAu6I148RmwWsGncSRqUaJrljOypaW9dS+GO4Ujjz3/lw1lrxSUh
IqVc0E7kyRW8kP3QCaNBwArYteHreZFFp6XmtKMtXaEA3saJYILxaaXlYkoRi4k8
S2/K8aw3ZMR4tDCOfB4o47JaeiA/e185RK3A+mLn9xTDhTdZqTQpv17/YRPcgmwz
zu30fhVXQT/SuI0sO+bzCO4YGoEwoBX718AWhdLJFoFq1B7k2ZEzXTAtjEXQEWm6
01ndU/jhAasdfasdasdfasdfa3eraszxqwefasdfadasdffsFIfAsjQb4HdkmHuC
OeJrJOd+CYvdEeqJJNnF6AbHyYHIECkj0Qq1kEfLOEsqzd5nDbtkKBte6M1trbjl
HtJ2Yb8w6o/q/6Sbj7wf/cW3LIYEdeVCjScozVcQ9R83ea05J+QOAr4nAoGBAMaq
UzLJfLNWZ5Qosmir2oHStFlZpxspax/ln7DlWLW4wPB4YJalSVovF2Buo8hr8X65
lnPiE41M+G0Z7icEXiFyDBFDCtzx0x/RmaBokLathrFtI81UCx4gQPLaSVNMlvQA
539GsubSrO4LpHRNGg/weZ6EqQOXvHvkUkm2bDDJAoGATytFNxen6GtC0ZT3SRQM
WYfasdf3xbtuykmnluiofasd2sfmjnljkt7khghmghdasSDFGQfgaFoKfaawoYeH
C2XasVUsVviBn8kPSLSVBPX4JUfQmA6h8HsajeVahxN1U9e0nYJ0sYDQFUMTS2t8
RT57+WK/0ONwTWHdu+KnaJECgYEAid/ta8LQC3p82iNAZkpWlGDSD2yb/8rH8NQg
9tjEryFwrbMtfX9qn+8srx06B796U3OjifstjJQNmVI0qNlsJpQK8fPwVxRxbJS/
pMbNICrf3sUa4sZgDOFfkeuSlgACh4cVIozDXlR59Z8Y3CoiW0uObEgvMDIfenAj
98pl3ZkCgYEAj/UCSni0dwX4pnKNPm6LUgiS7QvIgM3H9piyt8aipQuzBi5LUKWw
DlQC4Zb73nHgdREtQYYXTu7p27Bl0Gizz1sW2eSgxFU8eTh+ucfVwOXKAXKU5SeI
+MbuBfUYQ4if2N/BXn47+/ecf3A4KgB37Le5SbLDddwCNxGlBzbpBa0=
-----END RSA PRIVATE KEY-----"""

private_key = paramiko.RSAKey(file_obj=StringIO(key_str))
transport = paramiko.Transport(('10.0.1.40', 22))
transport.connect(username='wupeiqi', pkey=private_key)

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('df')
result = stdout.read()

transport.close()

print(result)

 

2.上传与下载文件

1)

下载上传,使用SSHclient封装的Transport,注意(连接建立完成以后需要关闭通道tran.close())

通过用户名密码demo:

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
#Author:wd
host=('172.16.11.35',22)
user='root'
passwd='1234qwer'
import paramiko
tran=paramiko.Transport(host)#host是一个tuple,分别是主机和port
tran.connect(username=user,password=passwd)
sftp=paramiko.SFTPClient.from_transport(tran)
status=sftp.put('socket_client.py','/usr/local/socket_client.py')#上传文件
sftp.get('/root/skip.sh','skip.sh')#下载文件
print(status)#打印传输状态
tran.close()#关闭连接

2)

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
#Author:wd
import paramiko
host=('172.16.11.35',22)
user='root'
private_key=paramiko.RSAKey.from_private_key_file('/Users/fangchaoliu/.ssh/id_rsa')
tran=paramiko.Transport(host)#host是一个tuple,分别是主机和port
tran.connect(username=user,pkey=private_key)
sftp=paramiko.SFTPClient.from_transport(tran)
status=sftp.put('socket_client.py','/usr/local/socket_client.py')#上传文件
sftp.get('/root/skip.sh','skip.sh')#下载文件
print(status)#打印传输状态
tran.close()#关闭连接

 

 

 

 

参考: https://www.cnblogs.com/wdliu/p/6858918.html

 

标签:key,stdout,python,tran,host,ssh,模块,paramiko
来源: https://www.cnblogs.com/xingxia/p/python_paramiko.html