This article provides a method that can capture the server's log files to the local machine and automatically analyze the log files according to the program. It is often used for data mining and production maintenance.
[Python]
Import OS
Import sys
Import ftplib
Import socket
######################################## ##########################
# Sign in the ftp server and download the log file.
# Log on to the production server to download logs
######################################## #########################
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)
Handle T (socket. error, socket. gaierror), e:
Print '---- ERROR: cannot reach' + host
Print e
Return False
# Login
Try:
F. login (user = userName, passwd = password)
Counter t 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)
Counter t 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)
Counter t 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'
Run: python getServerLog. py