paramiko 简单的使用

简介: 笔记

感觉自己操作服务器还要用xshell,麻烦很多,于是呢就去google,找到了paramiko。

使用这个模块还是很简单的,

我们链接服务器,只需要导入 SSHClient,AutoAddPolicy 两个类就可以使用了。


代码如下

# -*- coding: utf-8 -*-
# @Date    : 2018-07-07 11:56:22
# @Author  : leizi
from paramiko import  SSHClient
from paramiko import AutoAddPolicy
class Telecent(object):
    def __init__(self,host,username,password):
        self.host=host
        self.username=username
        self.password=password
    def telecent(self):#链接服务器
        ssh=SSHClient()
        ssh.set_missing_host_key_policy(AutoAddPolicy())
        try:
            ssh.connect(hostname=self.host,username=self.username,password=self.password,allow_agent=True)
            return ssh
        except Exception as e:
            raise e
    def exec_command(self,cmd):#执行命令
        try:
            stdin,stdout,stderr=self.telecent().exec_command(cmd)
            result=stdout.read()
            return str(result).encode('utf-8')
        except Exception as e:
            raise e
        finally:
            self.telecent().close()
    def copy_file(self,intputpath,outpath):#复制文件
        try:
            ftp=self.telecent().open_sftp()
            ftp.put(intputpath,outpath)
        except Exception as e:
            raise e
        finally:
            ftp.close()

我这里每次函数我都有异常处理,暂时针对异常呢,我这里处理的方式是直接抛出去。

在后续的,我会做进一步的处理,这个在以后我们的测试过程中是可以会遇到的。

这样就简单的 一个简单可以用的脚本就编写完了,在以后工作中还有进一步的作用。


相关文章
|
9月前
|
安全 Linux 网络安全
Python使用Paramiko实现SSH管理
paramiko 是一个用于在Python中实现SSHv2协议的库,它支持对远程服务器进行加密的通信。目前该模块支持所有平台架构且自身遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接,你可以在Python中实现SSH客户端和服务器,并进行安全的文件传输和远程命令执行。
101 0
|
Python Windows Unix
|
网络安全 数据安全/隐私保护 Python
|
网络协议 网络安全 Go
|
监控 网络安全 Python
|
网络安全 数据安全/隐私保护 Python
第三方模块paramiko的使用
  "Paramiko" is a combination of the Esperanto words for "paranoid" and "friend". It's a module for Python 2.
1054 0