Thursday 19 July 2018

how to copy file from FTP server to unix server using Python


I have a file in ftp server and i want to copy it to unix server every time where ever the script runs:


from ftplib import FTP_TLS
ftps = FTP_TLS('ftpservername', 'username', 'password','portnumber')
ftps.prot_p()
files = ftps.dir('/')
ftps.cwd("/ftp directory where file exist/")
filematch = 'filename'
target_dir = '/unix directory path where u want to copy the file/'
import os
for filename in ftps.nlst(filematch):
    target_file_name = os.path.join(target_dir,os.path.basename(filename))
    with open(target_file_name,'wb') as fhandle:
            ftps.retrbinary('RETR %s' %filename, fhandle.write)


Note : only you have to change the  red marked fields with your server/path details  .  

how to upload file from unix server to ftp server using Python


I have a file in unix box and i want to move it to ftp server box:


from ftplib import FTP_TLS
ftps = FTP_TLS('ftpservername', 'username', 'password','portnumber')
ftps.prot_p()
files = ftps.dir('/')
ftps.cwd("/ftpserver file path/")
localfile = '/unix file path where file exit/'
import os
fp = open(localfile, 'rb')
ftps.storbinary('STOR %s' % os.path.basename(localfile), fp, portnumber)
fp.close()
ftps.quit()


Note : only you have to change the  red marked fields with your server/path details  .