Created
October 27, 2017 17:33
-
-
Save victorusachev/d8a9b5dd42401890726582dd73848823 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# –*– encoding: UTF-8 –*– | |
'''ftp_updown.py: connection to FTP and up & down function''' | |
__author__ = 'frantisekrehor.cz' | |
__email__ = 'hi@frantisekrehor.cz' | |
#================================================================ | |
#importing necessary modules for running script | |
import os | |
import errno | |
import ftplib | |
#definitions of available methods | |
def ftp_connect(server, usr, pswd): | |
''' Creater connection object and login to FTP server ''' | |
try: | |
conn = ftplib.FTP(server) | |
conn.login(user = usr, passwd = pswd) | |
print 'Successfully connected to "%s"' % server | |
return conn | |
except ftplib.all_errors as e: | |
print "ftp error: %s" % e | |
def ftp_up(connection, path, data, file_output = None): | |
''' Uploading a file to FTP ''' | |
# file_output | |
if not file_output: | |
file_output = os.path.basename(os.path.realpath(data)) | |
try: | |
# changing FTP working directory | |
connection.cwd(path) | |
# open the file and upload | |
with open(file_output, 'rb') as out: | |
connection.storbinary('STOR ' + file_output, out) | |
print 'File "%s" successfully uploaded to "%s"' \ | |
% (file_output, path) | |
return True | |
except IOError as (errno, strerror): | |
print "I/O error(%r): %r" % (errno, strerror) | |
return False | |
except ftplib.all_errors as e: | |
print "ftp error: %s" % e | |
return False | |
def ftp_down(connection, path, data, file_output = None): | |
''' Downloading a file from FTP ''' | |
# file_output | |
if not file_output: | |
file_output = os.path.basename(os.path.realpath(data)) | |
try: | |
# changing FTP working directory | |
connection.cwd(path) | |
# open the file for writing and write data from FTP | |
with open(file_output, 'wb') as out: | |
connection.retrbinary('RETR ' + data, out.write) | |
print 'File "%s" successfully downloaded from "%s"' \ | |
% (file_output, path) | |
return True | |
except IOError as (errno, strerror): | |
print "I/O error(%r): %r" % (errno, strerror) | |
return False | |
except ftplib.all_errors as e: | |
print "ftp error: %s" % e | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment