当前位置:编程学习 > python >>

python: 从远程服务器下载日志程序

本文提供了一种方法,该程序可实现抓取服务器的日志文件到本地,根据该程序可自行扩展对日志文件的自动化分析。常用于数据挖掘、生产维护等。
[python] 
import os 
import sys 
import ftplib 
import socket 
 
################################################################## 
#    sign in the ftp server and download the log file.   
#    登陆生产服务器下载日志 
################################################################# 
def getServerLog(dir,fileName,host,userName,password): 
    if os.path.exists(fileName): 
        print '****the file '+ fileName +' has already exist! The file will be over writed'          
    #connect 
    try: 
        f=ftplib.FTP(host) 
    except (socket.error,socket.gaierror),e: 
        print '----ERROR:cannot reach '+host 
        print e 
        return False 
    #login     
    try: 
        f.login(user=userName,passwd=password) 
    except ftplib.error_perm ,e: 
        print '----ERROR:cannot login to server '+host 
        print e 
        f.quit() 
        return False 
    print '****Logged in as ' + userName + ' to server ' +host 
    #change folder 
    try: 
        f.cwd(dir) 
    except ftplib.error_perm,e: 
        print '----ERROR:cannot CD to %s on %s' % (dir,host) 
        print e 
        f.quit() 
        return False 
    print '**** changed to %s folder on %s' % (dir,host) 
    #get file 
    try: 
        f.retrbinary('RETR %s' % fileName,open(fileName,'wb').write) 
    except ftplib.error_perm,e: 
        print '----ERROR:cannot read file %s on %s' % (fileName,host) 
        print e 
        os.unlink(fileName) 
        return False 
    else: 
        print '****Downloaded '+ fileName +' from '+ host +' to '+os.getcwd() 
        f.quit() 
        return  True 
         
if __name__ == "__main__": 
    getServerLog("/userhome/root/other/temp","a.out","10.10.10.10","root","password") 
    print '****done' 
 
运行:python getServerLog.py

补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,