Friday, February 27, 2015

Python: Copy Folder or Files using password (sudo)

Following code can be used to copy Folder or Files using sudo with password.

   def copyFolderOrFile(self, sourcePath, destinationPath):  
     if(os.path.isdir(sourcePath)==True):  
       os.chdir("/some_root_location/")  
       sudoPassword = 'password_of_user_having_sudo_rights'  
       try:  
         command="cp -R "+sourcePath+" "+destinationPath  
         os.system('echo %s|sudo -S %s' % (sudoPassword, command))  
         print "Directory Copied Sucessfully"  
       except OSError as exc:  
         if exc.errno == errno.ENOTDIR:  
           command="cp "+sourcePath+" "+destinationPath  
           os.system('echo %s|sudo -S %s' % (sudoPassword, command))  
           print "File Copied Sucessfully"  
         else:  
           print('Directory/File not copied. Error: %s' % exc)  

More suggestion are always welcome. In case if you wish me to write about any specific scenario, please feel free to write to me or else you can Comment below.

No comments:

Post a Comment