首页 > 代码库 > python 下载远程日志

python 下载远程日志

# coding:utf-8

import paramiko
import time
import sys

# Create your views here.
# ====================================================
# Author: chang - EMail:changbo@hmg100.com
# Last modified: 2017-06-06
# Filename: updateversion.py
# Description: file upload ,base paramiko, sys, time
# blog:http://www.cnblogs.com/changbo
# ====================================================

iplist = [‘x.x.x.x‘]
accpwd = {iplist[0]: ‘xxxxx‘}
basefile = ‘/home/changbo‘
localpath = ‘/root/access.tar.gz‘
filename = ‘access.tar.gz‘
# targetpath = ‘%s‘ % basefile
targetpath = ‘%s/%s‘ % (basefile, filename)


class SSHSession:
    def __init__(self, host, pwd, username=‘changbo‘, port=22):
        self.host = host
        self.port = port
        self.username = username
        self.pwd = pwd

    def connect(self):
        transport = paramiko.Transport((self.host, self.port))
        transport.connect(username=self.username, password=self.pwd)
        self.__transport = transport

    def close(self):
        self.__transport.close()

    def progress_bar(self, transferred, toBeTransferred, suffix=‘‘):
        bar_len = 60
        filled_len = int(round(bar_len * transferred / float(toBeTransferred)))
        percents = round(100.0 * transferred / float(toBeTransferred), 1)
        bar = ‘=‘ * filled_len + ‘-‘ * (bar_len - filled_len)
        sys.stdout.write(‘Download [%s] %s%s ...%s\n‘ % (bar, percents, ‘%‘, suffix))
        sys.stdout.flush()

    def getloadfile(self, target_path, local_path):
        ssh = paramiko.SSHClient()
        ssh._transport = self.__transport
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        print(‘Download remote log file :‘)
        sftp.get(target_path, local_path, callback=self.progress_bar)


try:
    ssh = SSHSession(iplist[0], accpwd[iplist[0]])
    ssh.connect()
    ssh.getloadfile(targetpath, localpath)
except Exception as e:
    print(e)

 END!

python 下载远程日志