Search code examples
pythonubunturootsudoshutil

Python - Move files to root directory in Ubuntu


I have to move all files from a particular directory to a root directory by using Python script. I failed with the following code with [Errno 13] Permission denied error.

import shutil
import os

source = '../json' 
dest = '/var/www/json'
files = os.listdir(source)

for f in files:
    shutil.move(source+"/"+f, dest)

Is it possible to add sudo with this code or is there any other method to move files to root folder? I am working in Ubuntu16.04


Solution

  • I can think of three possible solutions to this:

    1. Running python as sudo: sudo python script.py. Probably not the nicest way as there are possible security concerns.
    2. Change the permissions of the folder so the user running the python script has access to copy/edit files in those folders.
    3. Call cp/mv as a subprocess from python as root. Basically the same as the first option. Can either be done by getting the user to type in root's password which I guess isn't great for you. Or you can use something like polkit to avoid using a password.

    I would suggest the 2nd option is best and easiest in the long run.