【Python之路Day12】网络篇之Paramiko

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

一、安装

pip3 install paramiko

二、使用

1. SSHClient

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

基于用户名密码连接:

 

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

import paramiko

#创建ssh对象

ssh = paramiko.SSHClient()

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

#连接服务器
ssh.connect(hostname='172.16.30.162',port=22,username='root',password='123456')

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

#获取执行结果
result = stdout.read()

print(result.decode()) #返回的是bytes

#关闭连接
ssh.close()
View Code

 

封装

基于公钥密钥连接:

 

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/Users/daniel/.ssh/id_rsa')

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='172.16.30.162', port=22, username='root', pkey=private_key)

# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()
print(result.decode())
# 关闭连接
ssh.close()
View Code

 

SFTPClient

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

基于用户名密码 上传/下载

 

#!/usr/bin/env python3
# -*- coding: utf-8 -*-)

import paramiko


transport = paramiko.Transport(('172.16.30.162',22))
transport.connect(username='root',password='123456')

sftp = paramiko.SFTPClient.from_transport(transport)

#上传本地文件/Users/daniel/test/zhoulibo.mp4 上传到服务器的 /tmp/zhoulibo.mp4
sftp.put('/Users/daniel/test/zhoulibo.mp4','/tmp/zhoulibo.mp4')

#将远端/tmp/zhoulibo.mp4 下载到 本地 /Users/daniel/zhoulibo.mp4
sftp.get('/tmp/zhoulibo.mp4','/Users/daniel/zhoulibo.mp4')

transport.close()
View Code

 

基于公钥/密钥的上传/下载:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/Users/daniel/.ssh/id_rsa')

transport = paramiko.Transport(('172.16.30.162',22))
transport.connect(username='root',pkey=private_key)

sftp = paramiko.SFTPClient.from_transport(transport)

#上传本地文件/Users/daniel/test/zhoulibo.mp4 上传到服务器的 /tmp/zhoulibo.mp4
sftp.put('/Users/daniel/test/zhoulibo.mp4','/tmp/zhoulibo.mp4')

#将远端/tmp/zhoulibo.mp4 下载到 本地 /Users/daniel/zhoulibo.mp4
sftp.get('/tmp/zhoulibo.mp4','/Users/daniel/zhoulibo.mp4')

transport.close()
View Code
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

import paramiko,uuid

class SSHConnection:

    def __init__(self,host='172.16.30.162',port=22,username='root',pwd='123456'):
        self.host = host
        self.port = port
        self.username = username
        self.pwd = pwd
        self.__k = None

    def create_file(self):
        file_name = str(uuid.uuid4())   #生成一个'46cad739-5937-4312-9156-00753b272581'的文件名 uuid并转换成str
        with open(file_name,'w') as f:  #打开文件,往里面写一个sb
            f.write('sb')
        return file_name

    def run(self):
        '''
        主方法
        :return:
        '''
        self.connect()
        self.upload('/tmp/test.py')   #调用upload方法,上传到服务器的/tmp/test.py
        self.rename('/tmp/test.py','/tmp/sb.py')  #改名为sb.py
        self.close()

    def connect(self):
        '''
        建立连接
        :return:
        '''
        transport = paramiko.Transport((self.host,self.port))
        transport.connect(username=self.username,password=self.pwd)
        self.__transport = transport

    def close(self):
        '''
        关闭连接
        :return:
        '''
        self.__transport.close()

    def upload(self,target_path):
        '''
        连接,上传
        :param target_path:
        :return:
        '''
        file_name = self.create_file()
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        #上传本地文件 到服务器的 test.py
        sftp.put(file_name, target_path)

    def rename(self, old_path, new_path):
        '''
        改名, 把/tmp/test.py 改名为 sb.py
        :param old_path:
        :param new_path:
        :return:
        '''
        ssh = paramiko.SSHClient()
        ssh._transport = self.__transport
        #执行命令
        cmd = "mv %s %s" %(old_path,new_path)
        stdin,stdout,stderr = ssh.exec_command(cmd)
        res = stdout.read()

    def cmd(self,command):
        '''
        可以执行其他命令
        :param command:
        :return:
        '''
        self.connect()
        ssh = paramiko.SSHClient()
        ssh._transport = self.__transport
        #执行命令
        stdin, stdout, stderr = ssh.exec_command(command)
        res = stdout.read()
        self.close()
        return res

ha = SSHConnection()

ha.run()
res = ha.cmd('ls')
print(res.decode())

Demo
Demo

 

posted @ 2016-07-29 14:25  莫问前程  阅读(273)  评论(0编辑  收藏  举报