python 下载远程日志

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 下载远程日志相关的知识,希望对你有一定的参考价值。

# coding:utf-8

import paramiko
import time
import sys

# Create your views here.
# ====================================================
# Author: chang - EMail:[email protected]
# 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 下载远程日志的主要内容,如果未能解决你的问题,请参考以下文章

python常用代码片段总结

argparse 代码片段只打印部分日志

Java远程实现Linux文件内容读取(通过远程执行shell命令分析日志)

Java远程实现Linux文件内容读取(通过远程执行shell命令分析日志)

Java远程实现Linux文件内容读取(通过远程执行shell命令分析日志)

Java远程实现Linux文件内容读取(通过远程执行shell命令分析日志)