python-Paramiko类的封装

对paramiko功能模块的封装,实现远程执行命令,文件上传下载功能

import paramiko

conf = {
    '196.168.41.222': ('root', 'root'),
}


class SSHConnection(object):
    def __init__(self, host, port):
        self._host = host
        self._port = port
        self._username = conf[host][0]
        self._password = conf[host][1]
        self._transport = None
        self._sftp = None
        self._client = None
        self._connect()  # 建立连接

    def _connect(self):
        transport = paramiko.Transport((self._host, self._port))
        transport.connect(username=self._username, password=self._password)
        self._transport = transport

    # 下载
    def download(self, remotepath, localpath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.get(remotepath, localpath)

    # 上传
    def put(self, localpath, remotepath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.put(localpath, remotepath)

    # 执行命令
    def exec_command(self, command):
        if self._client is None:
            self._client = paramiko.SSHClient()
            self._client._transport = self._transport
        stdin, stdout, stderr = self._client.exec_command(command)
        out_data = stdout.read().decode('utf-8').strip()
        returncode = stdout.channel.recv_exit_status()
        if len(out_data) > 0:
            # try:
            #     print(data.decode('utf-8').strip())
            # except UnicodeDecodeError:
            #     print(data.decode('gbk').strip())
            return out_data
        err_data = stderr.read().decode('utf-8').strip()
        if len(err_data) > 0:
            # try:
            #     print(err.decode('utf-8').strip())
            # except UnicodeDecodeError:
            #     print(err.decode('gbk').strip())
            return err_data
        # print("返回值:",returncode)
        return (returncode)

    def close(self):
        if self._transport:
            self._transport.close()
        if self._client:
            self._client.close()


# def run_ssh_command(ip,command):
#     conn = SSHConnection(ip,22)
#     if conn.exec_command(command):
#         return 1
#     else:
#         return 0

if __name__ == "__main__":
    conn = SSHConnection('196.168.41.222', 22)
    a = conn.exec_command('df -h')
    print(a)

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大帅不是我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值