本文介绍了Python的Paramiko模块,它是一个实现SSH2协议的库,用于进行加密和认证的远程服务器连接。示例展示了如何使用Paramiko进行远程密码连接、SFTP文件上传和下载,以及基于公钥的身份验证。此外,还提供了一个SSHUtils类,简化了SSH命令执行和SFTP操作。
paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。
paramiko远程密码连接
import paramiko
##1.创建一个ssh对象
client = paramiko.SSHClient()
#2.解决问题:如果之前没有,连接过的ip,会出现选择yes或者no的操作,
##自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#3.连接服务器
client.connect(hostname='172.25.254.31',
port=22,
username='root',
password='westos')
#4.执行操作
stdin,stdout, stderr = client.exec_command('hostname')
#5.获取命令执行的结果
result=stdout.read().decode('utf-8')
print(result)
#6.关闭连接
client.close()
import paramiko
#获取Transport实例
tran = paramiko.Transport("172.25.254.31",22)
#连接SSH服务端
tran.connect(username = "root", password = "westos")
#获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)
#设置上传的本地/远程文件路径
localpath="passwd.html" ##本地文件路径
remotepath="/home/kiosk/Desktop/fish" ##上传对象保存的文件路径
#执行上传动作
sftp.put(localpath,remotepath)
tran.close()
使用sftp下载文件
import paramiko
#获取SSHClient实例
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#连接SSH服务端
client.connect("172.25.254.31",username="root",password="westos")
#获取Transport实例
tran = client.get_transport()
#获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)
remotepath='/home/kiosk/Desktop/fish'
localpath='/home/kiosk/Desktop/fish'
sftp.get(remotepath, localpath)
client.close()
paramiko基于公钥密钥连接
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
def connect(cmd, hostname, port=22, user='root'):
client = paramiko.SSHClient()
private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
###id_rsa为本地局域网密钥文件
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=hostname,
port=port,
username=user,
pkey=private_key
)
stdin, stdout, stderr = client.exec_command(cmd)
except NoValidConnectionsError as e:
print("连接失败")
except AuthenticationException as e:
print("密码错误")
else:
result = stdout.read().decode('utf-8')
print(result)
finally:
client.close()
for count in range(254):
host = '172.25.254.%s' %(count+1)
print(host.center(50, '*'))
connect('uname', host)
基于密钥的上传和下载
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
tran = paramiko.Transport('172.25.254.31',22)
tran.connect(username='root',password='westos')
#获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)
remotepath='/home/kiosk/Desktop/fish8'
localpath='/home/kiosk/Desktop/fish1'
sftp.put(localpath,remotepath)
sftp.get(remotepath, localpath)
实战:
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
class SSHUtils(object):
'''
ssh连接工具
Eg:
ssh = SSHUtils(hostname='192.168.1.60', port=50022, username='root', password=' ')
print(ssh.cmd_run(cmd='ls'))
'''
def __init__(self, hostname, port, username, password):
"""
:param hostname: ip
:param port: 端口
:param username: 账号
:param password: 密码
"""
self._hostname = hostname
self._port = int(port)
self._username = username
self._password = password
def cmd_run(self, *, cmd):
"""
cmd操作
:returns 返回cmd操作的返回值
"""
_client = paramiko.SSHClient()
_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
_client.connect(hostname=self._hostname, port=self._port, username=self._username, password=self._password)
_result = _client.exec_command(str(cmd))
print(_result)
except NoValidConnectionsError:
return '连接失败'
except AuthenticationException:
return '账号密码错误'
return _result[1].read().decode('utf-8')
def sftp_run(self, location_file_path, obj_file_path, download=False):
"""
sftp上传文件 或 下载文件
:param location_file_path: 本地文件路径
:param obj_file_path: 服务器文件路径
:param download: 是否下载文件 默认:False
:return: Null
"""
tran = paramiko.Transport(self._hostname, self._port)
tran.connect(username=self._username, password=self._password)
sftp = paramiko.SFTPClient.from_transport(tran)
if download:
sftp.get(obj_file_path, location_file_path)
else:
sftp.put(location_file_path, obj_file_path)
tran.close()