3.09.2015 г.

Python copy folder from USB to map drive in windows machine

#! --*-- coding:utf-8 --*--

###################################
#    Uses for copy folder from,    #
#    USB drive to map used device  #
#                                  #
#    Do not edit by hand           #
###################################    

#Imort requeare module's
import os,subprocess,shutil,time,sys

#General param is here
remote_ip = 'ip'                    #ip for server
remote_share_folder = 'share'        #share folder from server
remote_user = 'Administrator'        #Username for server
remote_pass = 'pass'                #password name for server
local_folder = r'c:\test'            #local folder where looking for dirname
mapping_char = 'G:'                    #charackter for maping

date_now = str(time.ctime()).split()[2]+str(time.ctime()).split()[1]+str(time.ctime()).split()[-1]

#--------------------Begin Function ----------------------------------#

#first function


def copyDirectory(src, dest):
    """
    used shutil.copytree for copy from src to dest
    if have somthing wrong like folder exists copy stop
    and script close
    """
    try:
        shutil.copytree(src, dest)
        print "Success Copied folder!"
        #print (src,dest)
    # Directories are the same
    except:
        print "Somthing wrong with copy Bye!"
        sys.exit(1)

#second function

def clear_folder(local_folder):
    """
    rmtree delete folder even folder is not empty
    then makedirs recovers folder
    """
    shutil.rmtree(local_folder)
    os.makedirs(local_folder)

#third function
def list_usb_flash():
    """
    chdir use to goto in usb drive, then list drive for file
    for eny file give full path and parse to first function
    finaly up one step and begin second function
    """
    os.chdir(local_folder)
    for root,dirname,filename in os.walk(local_folder):
        for f in dirname:
            fol = os.path.join(root,f)
            copyDirectory(fol, (mapping_char+'\\'+f+"-"+date_now))
    os.chdir(r'c:\\')
    clear_folder(local_folder)
                
                

#---------------End function's------------------------------------------#    

if os.path.isdir(local_folder):
    print "Folder exists now begin..."
    if os.path.isdir(mapping_char):
        list_usb_flash()
        
    else:
        maping = subprocess.Popen('net use %s \\\\%s\%s /user:%s %s' % (mapping_char,remote_ip,remote_share_folder,remote_user,remote_pass),shell=True, stdout=subprocess.PIPE)
        list_usb_flash()
        
else:
    print "USB Driver maybe not mounted!!!"

.