Advertisement
zopper

fast ftp upload

May 3rd, 2011
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.57 KB | None | 0 0
  1. #!/usr/bin/python
  2. # Author: Jan Tulak <jan@tulak.me>
  3. #
  4. # You can feel free to do anything with this source as you want.
  5. #
  6. # NO WARRANTY!!!
  7. #
  8. # This script is for fast file upload on a ftp server.
  9. # You can create an shortcut with "-g" parameter, so you can simply drag'n drop any file
  10. # to it and this script upload the file and show its address in dialog.
  11. # Or you can add "-c" parameter and it will paste its address into clipboard,
  12. # or you can combine it.
  13. # If you give a directory instead of file, this script make an .tgz archive from it
  14. # and upload this archive (is using your temp dir)
  15.  
  16.  
  17. # settings - change to yourself
  18.  
  19. FTP_HOST='host'     # FTP server address
  20. FTP_USER='user'     # user for FTP
  21. FTP_PASS='pass'     # password for the user
  22.  
  23. FTP_DIR='your_dir/on/ftp'   # directory on FTP server, in which you want store files
  24.  
  25. retUrl='http://your-webhost/your_dir/on/ftp'    # URL which will be added to filename pasted into the clipboard
  26. retUrlDir='http://your-webhost/?show-files=true' # URL to a list of all uploaded files
  27.  
  28. # ----------------------------------------------------------------------------
  29. # HERE BEGIN SCRIPT
  30. # ----------------------------------------------------------------------------
  31.  
  32. from ftplib import FTP
  33. import os
  34. import urllib
  35. import sys
  36.  
  37. import pygtk
  38. pygtk.require('2.0')
  39. import gtk
  40.  
  41. import tarfile
  42. import tempfile
  43. import re
  44. import string
  45. # ----------------------------------------------------------------------------
  46. # vlastni tridy
  47. # ----------------------------------------------------------------------------
  48.  
  49. # trida na vlastni vyjimku
  50. class uploadError(Exception):
  51.     def __init__(self, value):
  52.     self.value = value
  53.     def __str__(self):
  54.       return repr(self.value)
  55.     def string(self):
  56.       return self.value
  57.      
  58.  # trida na vlastni zpravuu
  59. class uploadMsg(Exception):
  60.     def __init__(self, value):
  61.     self.value = value
  62.     def __str__(self):
  63.       return repr(self.value)
  64.     def string(self):
  65.       return self.value
  66.            
  67.  
  68. # ----------------------------------------------------------------------------
  69. # globalni promenne
  70. # ----------------------------------------------------------------------------
  71. debug=0
  72. useClipboard=0
  73. useGTK=0
  74.  
  75. # ----------------------------------------------------------------------------
  76. # definice funkci
  77. # ----------------------------------------------------------------------------
  78.    
  79. # tohle nahraje pres FTP zadany soubor na zadane spojeni
  80. def upload(conn, fname):
  81.     # pokud jde o adresar, vytvori archiv a zavola sebe sama s cestou k archivu
  82.     if os.path.isdir(fname):
  83.     if debug: print '"%s" is a dir - tgz must be created.' % fname
  84.     fname=os.path.abspath(fname) # aby slo pouzivat i veci jako "./"
  85.    
  86.     cregex=re.compile('/$')  # compile the search regexp
  87.     fname=cregex.sub('',fname) # nahradime koncove lomitko, kdyby uzivatel zadal cestu s nim
  88.     (head, tail) = os.path.split(fname) # zjistime nazev soubor/adresare
  89.     tmpDir=tempfile.gettempdir() # dostaneme temp dir
  90.     tar = tarfile.open(tmpDir+'/'+tail+'.tgz', "w:gz")
  91.     if debug: print 'Adding files to archive.'
  92.     tar.add(fname,arcname=tail)
  93.     tar.close()
  94.     upload(conn, tmpDir+'/'+tail+'.tgz') # zavolame se znova, tentokrat s cestou k archivu
  95.     # smazeme docasny archiv
  96.     os.remove(tmpDir+'/'+tail+'.tgz')
  97.     raise uploadMsg, tmpDir+'/'+tail+'.tgz'
  98.     #raise uploadError, "ERROR: %s is a dir!" % fname
  99.     # pokud jde o soubor, odesle ho
  100.     elif os.path.isfile(fname):
  101.     if debug: print 'Begin upload of "%s".' % fname
  102.     (head, tail) = os.path.split(fname) # zjistime nazev soubor/adresare
  103.     command = "STOR " + tail
  104.     fd = open(fname, 'rb')
  105.     temp = fd.read(2048)
  106.     fd.seek(0, 0)
  107.     if temp.find('\0') != -1:
  108.         conn.storbinary(command, fd)
  109.     else:
  110.         conn.storlines(command, fd)
  111.         fd.close()    
  112.     raise uploadMsg, tail
  113.     # neexistujici soubor
  114.     else:
  115.     raise uploadError, "ERROR: %s not exist!" % fname
  116.  
  117. # vytiskne napovedu    
  118. def usage():
  119.     print 'usage: '+sys.argv[0]+' [COMMAND] file1 file2 ...'
  120.     print 'COMMAND:'
  121.     print ' -h --help   Show this help'
  122.     print ' -d      Debug mode'
  123.     print ' -c      Store address to clipboar'
  124.     print ' -g      Show GTK Dialog'
  125.     print 'Tip:'
  126.     print 'You can create an desktop entry, combine -c and -g and simply drag and drop any file on it.'
  127.     print 'If you give a directory instead of file, this script make an .tgz archive from it a upload this archive (is using your temp dir).'
  128.     print 'Author: Jan Tulak <jan@tulak.me>'
  129.  
  130. # dialog
  131. def custom_dialog(dialog_type, title, message):
  132.     '''custom_dialog(dialog_type, title, message)
  133.  
  134.    This is a generic Gtk Message Dialog function.
  135.    dialog_type = this is a Gtk type. The options are:
  136.        gtk.MESSAGE_INFO
  137.        gtk.MESSAGE_WARNING
  138.        gtk.MESSAGE_ERROR
  139.    '''
  140.     dialog = gtk.MessageDialog(None,
  141.                                gtk.DIALOG_MODAL,
  142.                                type=dialog_type,
  143.                                buttons=gtk.BUTTONS_OK)
  144.     dialog.set_markup("<b>%s</b>" % title)
  145.     dialog.format_secondary_markup(message)
  146.     dialog.run()
  147.     dialog.destroy()
  148.  
  149. # ----------------------------------------------------------------------------
  150. # MAIN
  151. # ----------------------------------------------------------------------------
  152. # lets begin  
  153. if __name__ == "__main__":
  154.     if len(sys.argv) == 1:
  155.     usage()
  156.     sys.exit(0)
  157.  
  158.     targetFiles = []
  159.  
  160.     # parametry
  161.     i=0
  162.     for arg in sys.argv:                
  163.     if arg in ("-h", "--help"):      
  164.         usage()                    
  165.         sys.exit(0)                  
  166.     elif arg == '-d':    
  167.         if len(sys.argv) == 2:
  168.         usage()
  169.         sys.exit(0)                
  170.         debug = 1            
  171.     elif arg == '-c':
  172.         if len(sys.argv) == 2:
  173.         usage()
  174.         sys.exit(0)          
  175.         useClipboard = 1
  176.     elif arg == '-g':
  177.         if len(sys.argv) == 2:
  178.         usage()
  179.         sys.exit(0)          
  180.         useGTK = 1
  181.     elif i > 0:
  182.         targetFiles.append(arg)
  183.     i=i+1
  184.     # vytvoreni FTP spojeni    
  185.     #
  186.     # Create an instance of the FTP object
  187.     # Optionally, you could specify username and password:
  188.     # FTP('hostname', 'username', 'password')
  189.     #ftp = FTP('tulak.me','tulakme','C4dRr40fb4')
  190.     ftp = FTP(FTP_HOST)
  191.  
  192.     # Log in to the server
  193.     if debug: print 'Logging in.'
  194.     # You can specify username and password here if you like:
  195.     try:
  196.     res=ftp.login(FTP_USER,FTP_PASS)
  197.     if debug: print res
  198.     # Otherwise, it defaults to Anonymous
  199.     #print ftp.login()
  200.     except:
  201.     # error dialog
  202.     message_type = gtk.MESSAGE_ERROR
  203.     error_title = "ERROR!"
  204.     error_description = "Cannot connect to server"
  205.     custom_dialog(message_type, error_title, error_description)
  206.     print 'Cannot connect'
  207.     exit(1)
  208.    
  209.  
  210.     # zkusime vlezt do adresare a nahrat tam soubor
  211.     try:
  212.     if debug: print 'Changing to ' + FTP_DIR
  213.     res=ftp.cwd(FTP_DIR)
  214.     if debug: print res
  215.     retUrlWithFile=""
  216.     for targetFile in targetFiles:
  217.         try:
  218.         res=upload(ftp, targetFile)
  219.         if debug: print res
  220.        
  221.         except uploadMsg,msg:
  222.         retUrlWithFile = retUrlWithFile+retUrl+urllib.quote(msg.string())+'\n'
  223.         print retUrl+urllib.quote(os.path.basename(msg.string()))
  224.         if debug: print 'File/dir was uploaded successfuly.'
  225.         except uploadError,msg:  
  226.         if useGTK:
  227.             # error dialog
  228.             message_type = gtk.MESSAGE_ERROR
  229.             error_title = "ERROR!"
  230.             error_description = "Cannot upload file:\n"+msg.string()
  231.             custom_dialog(message_type, error_title, error_description)
  232.         sys.exit("Cannot upload file:\n"+msg.string()) # chyba souboru - neexistuje a podobne
  233.  
  234.     except:
  235.     if useGTK:
  236.         # error dialog
  237.         message_type = gtk.MESSAGE_ERROR
  238.         error_title = "ERROR!"
  239.         error_description = "Cannot upload file due an error."
  240.         custom_dialog(message_type, error_title, error_description)
  241.     sys.exit('ERROR: Cannot upload file due an error.') # nejaka chyba od ftp knihovny
  242.    
  243.     # chceme ulozit do clipboardu
  244.     if useClipboard:
  245.     # get the clipboard
  246.     clipboard = gtk.clipboard_get()
  247.     # set the clipboard text data
  248.     clipboard.set_text(retUrlWithFile)
  249.     # make our data available to other applications
  250.     clipboard.store()
  251.     # chceme zobrazit dialog
  252.     if useGTK:
  253.     # Info dialog
  254.     message_type = gtk.MESSAGE_INFO
  255.     info_title = "File was succesfully uploaded"
  256.     info_description = "File was succesfully uploaded"
  257.    
  258.     if useClipboard:
  259.         info_description=info_description+" and addres stored in the clipboard"
  260.    
  261.     info_description=info_description+":\n\n" + retUrlWithFile +"\n"+\
  262.     "<a href='"+retUrlDir+"'>List of files</a>"
  263.    
  264.     custom_dialog(message_type, info_title, info_description)
  265.      
  266.    
  267.     if debug: print 'Closing FTP connection'
  268.     ftp.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement