介绍
paramiko 遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接,可以实现远程文件的上传,下载或通过ssh远程执行命令。
项目地址:https://github.com/paramiko/paramiko
官方文档:http://docs.paramiko.org/
使用pip3安装
pip3 install paramiko
上一篇章已经讲诉了使用密码访问的方式 python3 paramiko 远程执行 ssh 命令、上传文件、下载文件 , 下面来看看封装使用RSA公钥访问的方式。
文件结构
[root@centos7 test_log]# tree paramiko-example/
paramiko-example/
├── file3.txt
├── file4.txt
├── paramiko_test.py
└── performance_rsa_4096
0 directories, 4 files
[root@centos7 test_log]#
封装示例代码 paramiko_test.py
import paramiko
import os
class ParamikoHelper():
def __init__(self,remote_ip, remote_ssh_port, private_key_file, ssh_username ):
self.remote_ip = remote_ip
self.remote_ssh_port = remote_ssh_port
self.ssh_username = ssh_username
self.private_key = paramiko.RSAKey.from_private_key_file(private_key_file) # 实例化一个私钥对象
def connect_ssh(self):
try:
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=self.remote_ip, port=self.remote_ssh_port, username=self.ssh_username,
pkey=self.private_key)
except Exception as e:
print(e)
return self.ssh
def close_ssh(self):
try:
self.ssh.close()
except Exception as e:
print(e)
def exec_shell(self, shell):
ssh = self.connect_ssh()
try:
stdin, stdout, stderr = ssh.exec_command(shell)
return stdin, stdout, stderr
except Exception as e:
print(e)
def sftp_put_file(self, file, local_dir, remote_dir):
try:
t = paramiko.Transport((self.remote_ip, self.remote_ssh_port))
t.connect(username=self.ssh_username, pkey=self.private_key)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(os.path.join(local_dir, file), remote_dir)
t.close()
except Exception:
print("connect error!")
def sftp_get_file(self, file, local_dir, remote_dir):
try:
t = paramiko.Transport((self.remote_ip, self.remote_ssh_port))
t.connect(username=self.ssh_username, pkey=self.private_key)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(remote_dir, os.path.join(local_dir, file))
t.close()
except Exception:
print("connect error!")
def main():
remote_ip = '192.168.196.134'
remote_ssh_port = 22
ssh_username = 'root'
private_key_file = 'performance_rsa_4096' # RSA私钥
ph = ParamikoHelper(remote_ip=remote_ip,remote_ssh_port=remote_ssh_port,private_key_file=private_key_file,ssh_username=ssh_username)
# 远程执行ssh命令
shell = "df -h | grep dev"
stdin, stdout, stderr = ph.exec_shell(shell)
for line in stdout.readlines():
print(line)
ph.close_ssh()
# 上传文件file4.txt到远程服务器上
file = 'file4.txt'
remote_dir = '/root/test_log/' + file
local_dir = os.getcwd()
ph.sftp_put_file(file=file, local_dir=local_dir, remote_dir=remote_dir)
# 下载文件file3.txt
file = 'file3.txt'
remote_dir = '/root/test_log/' + file
local_dir = os.getcwd()
ph.sftp_get_file(file=file, local_dir=local_dir, remote_dir=remote_dir)
if __name__ == '__main__':
main()