paramiko
浏览量:1015
paramiko简介
paramiko 遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接,可以实现远程文件的上传,下载或通过ssh远程执行命令
项目地址:https://github.com/paramiko/paramiko
官方文档:http://docs.paramiko.org/
下载安装
pip install paramiko
建立ssh连接
使用密码连接
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__Author__ = "YoungCheung"
import paramiko
#
IP="xx.xx.xx.xx"
username='xx'
password='xxxxxxx'
try:
ssh = paramiko.SSHClient()
# 这行代码的作用是允许连接不在know_hosts文件中的主机。
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IP, 22, username, password)
print("connect success")
except Exception as e:
print(e)使用私钥连接
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__Author__ = "YoungCheung"
import paramiko , os
hostname='xx.xx.xx.xx'
username='zhangyang'
paramiko.util.log_to_file('paramiko.log')
try:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
# 定义私钥存放另=路径
privatekey = os.path.expanduser('~/.ssh/id_rsa')
# 创建私钥对象key
key = paramiko.RSAKey.from_private_key_file(privatekey)
ssh.connect(hostname=hostname, username=username, pkey=key)
print("connect succeed")
stdin, stdout, stderr = ssh.exec_command('route -n')
res=stdout.readlines()
for res_result in res:
print(res_result.strip())
except Exception as e:
print(e)执行命令
ssh.exec_command('ls')
(<paramiko.ChannelFile from <paramiko.Channel 0 (open) window=2097152 -> <paramiko.Transport at 0x4088f98 (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>, <paramiko.ChannelFile from <paramiko.Channel 0 (open) window=2097152 -> <paramiko.Transport at 0x4088f98 (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>, <paramiko.ChannelFile from <paramiko.Channel 0 (open) window=2097152 -> <paramiko.Transport at 0x4088f98 (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>)执行shell命令以后,并不会立即打印命令的执行结果,而是返回几个Channel, 只能像下面这样获取输出:
stdin, stdout, stderr = ssh.exec_command('ls')
print(stdout.readlines())
['2\n', 'nginx-1.15.2\n', 'nginx-1.15.2.tar.gz\n', 'service\n', 'test\n']注意: 命令执行出错并不会抛出异常,所以,对于命令出错需要根据自己的需求进行相应的处理
文件的上传下载
通过paramiko还可以传输文件,这是我写这篇博客的主要原因。搜了很多博客,都没有说明白如何通过paramiko在计算机之间传输文件,通过阅读官方文档,发现有如下两种方式:
sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) sftp = ssh.open_sftp()
文件上传
#sftp.put('/Users/zhangyang/test/svn/1.txt', '/home/ctmp/test/1.txt')#!/usr/bin/env python
# -*- coding:utf-8 -*-
__Author__ = "YoungCheung"
import paramiko,datetime,os
hostname = 'xx.xx.xx.xx'
username = 'xxxx'
password = 'xxxxxx'
port = 22
local_dir = '/Users/zhangyang/test/svn/'
remote_dir = '/home/ctmp/test'
try:
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
files = os.listdir(local_dir)
count = 0
for f in files:
sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f))
count += 1
if count == len(files):
print(str(count) + ' files put successful')
else:
print('put failure')
t.close()
except Exception:
print("connect error!")文件下载
#sftp.get('/home/ctmp/test/1.txt','/Users/zhangyang/test/svn/1.txt')#!/usr/bin/env python
# -*- coding:utf-8 -*-
__Author__ = "YoungCheung"
import paramiko,datetime,os
hostname = 'xx.xx.xx.xx'
username = 'xxxx'
password = 'xxxxxx'
port = 22
local_dir = '/Users/zhangyang/test/svn/'
remote_dir = '/home/ctmp/test'
try:
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
files = sftp.listdir(remote_dir) #这里需要注意,列出远程文件必须使用sftp,而不能用os
count = 0
for f in files:
sftp.get(os.path.join(remote_dir,f),os.path.join(local_dir,f))
count += 1
if count == len(files):
print(str(count) + ' files get successful')
else:
print('get failure')
t.close()
except Exception:
print("connect error!")扩展
更多sftp命令参考:
https://paramiko-docs.readthedocs.io/en/1.15/api/sftp.html

神回复
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。