Python: Download a log program from a remote server

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.