Python3-paramiko模块-基于SSH的远程连接模块

Python3中的paramiko模块,基于SSH用于连接远程服务器并执行相关操作

  http://docs.paramiko.org/en/2.1/

SSHClient 用于连接远程服务器并执行基本命令

import paramiko

# 创建SSH客户端对象
ssh = paramiko.SSHClient()

# 允许连接不再know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接服务器
ssh.connect(hostname="172.16.110.218", port=22, username="root", password="******")

# 执行命令
stdin, stdout, stderr = ssh.exec_command("ls /local/jet")

# 获取命令执行结果
result = stderr.read()
result = result if result else stdout.read()
print(str(result.decode("gbk")))

# 关闭连接
ssh.close()
1.使用用户名密码连接

import paramiko

# 读取私钥文件
private_key = paramiko.RSAKey.from_private_key_file("e:\\id_rsa")

# 创建SSH对象
ssh = paramiko.SSHClient()

# 允许连接不再known_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接服务器
ssh.connect(hostname="172.16.110.218", port=22, username="root", pkey=private_key)

# 执行命令
stdin, stdout, stderr = ssh.exec_command("ls /local/jet")
# 获取命令执行结果
result = stderr.read()
result = result if result else stdout.read()
print(str(result.decode("gbk")))

# 关闭连接
ssh.close()
2.使用私钥文件连接

import paramiko
from io import StringIO

key_str = """-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEA6eXFQDFRT+tbtnsw44+16fZa1cZF7nouFVRuIuEZx93Gu9Kr
jBW2MFO/uyREHFK20xQzfX/jcD6/R1Yxh7jtLtN/uIUC3mV6yV/WjTmidH1ABlvq
wWyF2i6Q0ZS3bmznuvi/Z1BVJQan9DaH17aQSA/xsKM08OPEO8PK7tuaXlzokj/7
Tb14vOUnxN8C79iBcifoIlq6zpu2SlJpu/YUc3jX6nqJEtG/XwYHfTvwXGwlLCtD
VOb8NtwjggmRbELNZ6QCY8rNo+xUP+9tnp6xa6io8gDg7yswaAvQBxe3F6NZCtc/
sOceTKUIosYZi45tDqfL9YashOvbUNjkSLXQZQIBIwKCAQANXZY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/PRzsffdKuPjm9tTZu9hVBW8CzJD1byaeT8czjKtzv
kKwhV8yqG0ZGqmGbxc00zJLh4pk1J45Nh0dLzAD0T6SskmmJQrJ+k1KPFzqDHj1H
9KRVifIb6WKYBdWF6JXo2nBhlsSymBGPXSnY4YXbsNfWGQDm6g==
-----END RSA PRIVATE KEY-----
"""
private_key = paramiko.RSAKey(file_obj=StringIO(key_str))

# 连接服务器
transport = paramiko.Transport(('172.16.110.218', 22))
transport.connect(username='root', pkey=private_key)
ssh = paramiko.SSHClient()
ssh._transport = transport

# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')

# 获取命令执行结果
result = stderr.read()
result = result if result else stdout.read()
print(str(result.decode("gbk")))

# 关闭连接
transport.close()
3.使用私钥字符串连接

SFTPClient 用于连接远程服务器并执行上传下载

import paramiko

# 连接远程服务器
transport = paramiko.Transport(("172.16.110.218", 22))
transport.connect(username="root", password="*****")

# 生成SFTPClient对象
sftp = paramiko.SFTPClient.from_transport(transport)

# 上传文件get('local_path', 'remote_path')
sftp.put("/local/script/demo.py", "e:\\demo.py")
# 下载文件get('remote_path','local_path')
sftp.get("e:\\demo.py", "/local/script/demo.py")

# 关闭连接
transport.close()
1.实现与远程服务器的文件上传与下载

参考资料

  http://www.cnblogs.com/wupeiqi/articles/5095821.html

  http://www.cnblogs.com/qq1207501666/p/6780469.html

posted on 2017-04-28 11:03  AustralGeek  阅读(344)  评论(0编辑  收藏  举报

导航