We are going to see about File download from Unix or Linux server to your window machine using Python script.
There are 2 steps involved:
1> First establish the FTP connection
2> Download the files based on your needs
'''
filedownload.py
'''
# import required modulesa
from ftplib import FTP
import os
#Define the variables
ftpServer = 'yyy.com' # or specify the IP address of the server
ftpUser = 'userx'
ftpPass = 'userpwd'
ftpFilePath = '/home/user/work/'
localDir = "C:\download"
# Function to connect FTP server
def ftpConnect():
ftp = FTP(ftpServer)
ftp.login(ftpUser,ftpPass)
print ftp.sendcmd('pwd') # print the default home directory
downloadFiles(ftp,ftpFilePath)
ftp.quit()
# start downloading the files
downloadFiles(ftp,ftpFilePath):
fileLists = []
# create a local windows directory if does not exists
if not os.path.isdir(localFeedDir):
os.mkdir(localDir)
# Set the current working directory as the folder you want to download
ftp.cwd(path)
ftp.retrlines('LIST',fileLists.append) #Lists out the files and directories
print "length is", len(fileLists) # prints the number of files in a directory
for i in range(len(fileLists)): # extract only file name
words = fileLists[i].split(None, 8)
filename = words[-1].lstrip()
local_filename = os.path.join(r"%s" %localDir, filename)
lf = open(local_filename, "wb")
ftp.retrbinary("RETR " + filename, lf.write, 8*1024)
lf.close()
def main():
ftpConnect()
Python Doc
There are 2 steps involved:
1> First establish the FTP connection
2> Download the files based on your needs
'''
filedownload.py
'''
# import required modulesa
from ftplib import FTP
import os
#Define the variables
ftpServer = 'yyy.com' # or specify the IP address of the server
ftpUser = 'userx'
ftpPass = 'userpwd'
ftpFilePath = '/home/user/work/'
localDir = "C:\download"
# Function to connect FTP server
def ftpConnect():
ftp = FTP(ftpServer)
ftp.login(ftpUser,ftpPass)
print ftp.sendcmd('pwd') # print the default home directory
downloadFiles(ftp,ftpFilePath)
ftp.quit()
# start downloading the files
downloadFiles(ftp,ftpFilePath):
fileLists = []
# create a local windows directory if does not exists
if not os.path.isdir(localFeedDir):
os.mkdir(localDir)
# Set the current working directory as the folder you want to download
ftp.cwd(path)
ftp.retrlines('LIST',fileLists.append) #Lists out the files and directories
print "length is", len(fileLists) # prints the number of files in a directory
for i in range(len(fileLists)): # extract only file name
words = fileLists[i].split(None, 8)
filename = words[-1].lstrip()
local_filename = os.path.join(r"%s" %localDir, filename)
lf = open(local_filename, "wb")
ftp.retrbinary("RETR " + filename, lf.write, 8*1024)
lf.close()
def main():
ftpConnect()
Useful Links:
Python Doc
No comments:
Post a Comment