zoukankan      html  css  js  c++  java
  • Python--paramiko库:连接远程服务器操作文件

    import paramiko
    from loggingutils.mylogger import logger as log


    class SSHConnection(object):
    def __init__(self, host, port, username, password):
    self._host = host
    self._port = port
    self._username = username
    self._password = password
    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)
    data = stdout.read()
    if len(data) > 0:
    log.info(data.decode('utf-8'))
    return data.decode('utf-8')
    err = stderr.read()
    if len(err) > 0:
    log.error(err.decode('utf-8'))
    return err

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


    if __name__ == "__main__":
    hostname = 'xxxxxxxxxxxx'
    port = 22
    username = 'xxxxx'
    password = 'xxxxxxxx'
    command = 'ls'
    conn = SSHConnection(hostname, port, username, password)
    localpath = 'E:/1.log'
    remotepath = '/logs/laravel.log'
    print('-----------downlaod start--------------')
    conn.download(remotepath, localpath)
    print('-----------download end----------------')
    print('-----------put begin-------------------')
    conn.put(localpath, remotepath)
    print('-----------put end---------------------')
    conn.exec_command(command)
    print('--------------------------------')
    conn.exec_command('pwd')
    print('--------------------------------')
    conn.exec_command('ls -l')
    conn.close()


  • 相关阅读:
    MySQL基础学习笔记
    网络编程入门笔记
    JUC并发编程学习笔记
    育儿技巧
    无法下载安装文件,请检查internet连接
    用户 'NT ServiceSSISScaleOutMaster140' 登录失败
    Javascript中apply、call、bind
    JQuery 源码解析一
    docker容器中部署 kafka 和 elk
    查找库中所有表所有字段中某个指定的字符
  • 原文地址:https://www.cnblogs.com/fqfanqi/p/8431791.html
Copyright © 2011-2022 走看看