Advertisement
Guest User

Untitled

a guest
May 20th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.46 KB | None | 0 0
  1. # -*- encoding:utf-8 -*-
  2. ''' Send files through FTPS '''
  3.  
  4. # FTP Defaults
  5. FTP_ADDRESS = '127.0.0.1'
  6. FTP_PORT = 21
  7. FTP_USER = 'ftp'
  8. FTP_PASSWORD = ''
  9. # Folder name format
  10. # %a    Locales abbreviated weekday name.
  11. # %A    Locales full weekday name.  
  12. # %b    Locales abbreviated month name.      
  13. # %B    Locales full month name.    
  14. # %c    Locales appropriate date and time representation.    
  15. # %d    Day of the month as a decimal number [01,31].    
  16. # %H    Hour (24-hour clock) as a decimal number [00,23].    
  17. # %I    Hour (12-hour clock) as a decimal number [01,12].    
  18. # %j    Day of the year as a decimal number [001,366].  
  19. # %m    Month as a decimal number [01,12].  
  20. # %M    Minute as a decimal number [00,59].      
  21. # %p    Locales equivalent of either AM or PM.
  22. # %S    Second as a decimal number [00,61].
  23. # %U    Week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  24. #       All days in a new year preceding the first Sunday are considered to be in week 0.
  25. # %w    Weekday as a decimal number [0(Sunday),6].  
  26. # %W    Week number of the year (Monday as the first day of the week) as a decimal number [00,53].
  27. #       All days in a new year preceding the first Monday are considered to be in week 0.
  28. # %x    Locales appropriate date representation.    
  29. # %X    Locales appropriate time representation.    
  30. # %y    Year without century as a decimal number [00,99].    
  31. # %Y    Year with century as a decimal number.  
  32. # %Z    Time zone name (no characters if no time zone exists).  
  33. # %%    A literal '%' character.
  34. FOLDER_NAME_FORMAT = '%d.%m.%Y'
  35.  
  36.  
  37. import sys, os, time, ftplib#, socket
  38.  
  39. # M2Crypto required
  40. try:
  41.     import M2Crypto
  42. except:
  43.     print 'Error: M2Crypto is not found. Please install it and rerun script.'
  44.     sys.exit(1)
  45.  
  46. log = open('ftps_send.log', 'w')
  47.  
  48. def connect_ftps(address, port, login, password):
  49.     ''' Connect to FTPS '''
  50.     #socket.setdefaulttimeout(50.0)
  51.     conn = M2Crypto.ftpslib.FTP_TLS()
  52. #    conn = ftplib.FTP()
  53.     conn.connect(address, port)
  54.     conn.auth_tls()
  55.     conn.set_pasv(0)
  56.     conn.login(login, password)
  57.     conn.prot_p()
  58. #    conn.voidcmd('TYPE I')
  59.     return conn
  60.    
  61. def send_file(conn, file_name):
  62.     ''' Send file through connection.
  63.        Very slow due to bug in ftplib.
  64.    '''
  65.     global log
  66.     log.write('send_file(' + file_name + ')\n')
  67.     f = open(file_name, 'rb')
  68.     try:
  69.         conn.storbinary('STOR ' + os.path.basename(file_name), f)
  70.     except ftplib.error_reply, e:
  71.         log.write(str(e) + '\n')
  72.     except ftplib.all_errors, e:
  73.         log.write(str(e) + '\n')
  74.         code = int(str(e).split()[0])
  75.         if code not in [200, 250, 451, 550]:
  76.             raise e          # everything else is very bad
  77.     f.close()
  78.  
  79. def send_file2(conn, file_name):
  80.     ''' Send file through connection.
  81.        Transfer delay bug workaround.
  82.    '''
  83.     global log
  84.     log.write('send_file2(' + file_name + ')\n')
  85.     try:
  86.         conn.voidcmd('TYPE I')
  87.         #conn.set_pasv(True)
  88.         sock = conn.transfercmd('STOR ' + os.path.basename(file_name)) # the data socket
  89.     except ftplib.error_reply, e:
  90.         log.write(str(e) + '\n')
  91.     except ftplib.all_errors, e:
  92.         log.write(str(e) + '\n')
  93.         code = int(str(e).split()[0])
  94.         if code not in [200, 250, 451, 550]:
  95.             raise e          # everything else is very bad
  96.  
  97.     f = open(file_name, 'rb')
  98.     sock.send(f.read())
  99.     sock.close()
  100.     f.close()
  101.  
  102. def create_dir(conn, dir_name, cd=False):
  103.     ''' Creates directory and optionally changes into it.
  104.    '''
  105.     log.write('create_dir(' + dir_name + ', ' + str(cd) + ')\n')
  106.     try:
  107.         conn.mkd(dir_name)
  108.         #conn.voidcmd('SITE CHMOD 0751 ' + dir_name)
  109.     except ftplib.error_reply, e:
  110.         log.write(str(e) + '\n')
  111.     except ftplib.all_errors, e:
  112.         log.write(str(e) + '\n')
  113.         code = int(str(e).split()[0])
  114.         if code not in [200, 250, 451, 550]:      # it is ok for dir to exists
  115.             raise e          # everything else is very bad
  116.     if cd:
  117.         log.write('cd ' + dir_name + '\n')
  118.         try:
  119.             conn.cwd(dir_name)
  120.         except ftplib.error_reply, e:
  121.             log.write(str(e) + '\n')
  122.         except ftplib.all_errors, e:
  123.             log.write(str(e) + '\n')
  124.             code = int(str(e).split()[0])
  125.             if code not in [200, 250, 451, 550]:
  126.                 raise e          # everything else is very bad
  127.  
  128. def process_dir(conn, directory):
  129.     ''' Process local directory.
  130.    '''
  131.     log.write('process_dir()\n')
  132.     for subdir, dirs, files in os.walk(directory):
  133.         for sdir in dirs:
  134.             #print 'dir', directory, sdir
  135.             create_dir(conn, sdir, True)
  136.             process_dir(conn, os.path.join(directory, sdir))
  137.         for i in range(len(dirs)): del dirs[0]
  138.            
  139.         for file_name in files:
  140.             #print 'file', directory, file_name
  141.             send_file2(conn, os.path.join(directory, file_name))
  142.     log.write('cd ..\n')
  143.     conn.cwd('..')
  144.    
  145. def usage():
  146.     print 'Usage:', sys.argv[0],'[OPTION]...'
  147.     print 'Uploads file from local directory to FTPS server.'
  148.     print 'You should specify at least --local-dir.'
  149.     print ''
  150.     print '--host\t\t\tFTPS server address'
  151.     print '--port\t\t\tFTPS server port'
  152.     print '--user\t\t\tuser name to log in with'
  153.     print '--password\t\tuser password to log in with'
  154.     print '--local-dir\t\tlocal directory with files to upload'
  155.     print '--remote-dir\t\tbase directory on remote server'
  156.     print '--folder-format\t\tcreate folder on server with format'
  157.    
  158. def main():
  159.     ''' Main function
  160.    '''
  161.     # Process arguments
  162.     ftp_address = FTP_ADDRESS
  163.     ftp_port = FTP_PORT
  164.     ftp_user = FTP_USER
  165.     ftp_password = FTP_PASSWORD
  166.     local_dir = None
  167.     remote_dir = '/'
  168.     folder_name_format = FOLDER_NAME_FORMAT
  169.     #
  170.     for i in range(len(sys.argv)):
  171.         if sys.argv[i] == '--host':
  172.             if len(sys.argv) < i + 2:
  173.                 usage()
  174.                 sys.exit(1)
  175.             ftp_address = sys.argv[i + 1]
  176.         if sys.argv[i] == '--port':
  177.             if len(sys.argv) < i + 2:
  178.                 usage()
  179.                 sys.exit(1)
  180.             ftp_port = int(sys.argv[i + 1])
  181.         if sys.argv[i] == '--user':
  182.             if len(sys.argv) < i + 2:
  183.                 usage()
  184.                 sys.exit(1)
  185.             ftp_user = sys.argv[i + 1]
  186.         if sys.argv[i] == '--password':
  187.             if len(sys.argv) < i + 2:
  188.                 usage()
  189.                 sys.exit(1)
  190.             ftp_password = sys.argv[i + 1]
  191.         if sys.argv[i] == '--local-dir':
  192.             if len(sys.argv) < i + 2:
  193.                 usage()
  194.                 sys.exit(1)
  195.             local_dir = sys.argv[i + 1]
  196.         if sys.argv[i] == '--remote-dir':
  197.             if len(sys.argv) < i + 2:
  198.                 usage()
  199.                 sys.exit(1)
  200.             remote_dir = sys.argv[i + 1]
  201.         if sys.argv[i] == '--folder-format':
  202.             if len(sys.argv) < i + 2:
  203.                 usage()
  204.                 sys.exit(1)
  205.             folder_name_format = sys.argv[i + 1]
  206.     if local_dir is None:
  207.         usage()
  208.         sys.exit(1)
  209.  
  210.     conn = connect_ftps(ftp_address, ftp_port, ftp_user, ftp_password)
  211.     conn.cwd(remote_dir)
  212.     dir_name = time.strftime(folder_name_format, time.localtime())
  213.     create_dir(conn, dir_name, True)
  214.     #send_file2(conn, 'testfile')
  215.     print 'Uploading...'
  216.     process_dir(conn, local_dir)
  217.     conn.quit()
  218.  
  219. main()
  220. log.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement