Cómo modificar permisos de ficheros y directorios con python

Muchas veces cuando instalas en un servidor algún plugin o algún cms, como prestashop, te crean permisos de lectura, escritura y ejecución que no son los más adecuados para la seguridad del servidor. Personalmente me molesta especialmente encontrarme con directorios y ficheros con 777.

Modificar a mano una cantidad muy grande de ficheros y directorios puede requerir mucho tiempo así que he preparado un pequeño script en python que hace esas modificaciones por mi. Sólo hay que cambiar el string ruta_a_explorar por el path y el sólo modifica los ficheros y directorios dejando los permisos 644 para los ficheros y 755 para los directorios.

Espero que os sea útil.

#! /usr/bin/env python
# -*- coding: utf-8-*-
import os, sys, stat
 
 
ruta_a_explorar="/ruta/a/explorar/"
 
for root,dirs,files in os.walk(ruta_a_explorar):
        for file in [f for f in files]:
                pp=os.path.join(root, file).replace("""\\""",'/')
                if stat.S_ISDIR(os.stat(pp)[stat.ST_MODE]):
                        os.chmod(pp,stat.S_IRWXU|stat.S_IWUSR|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH)
                elif stat.S_ISREG(os.stat(pp)[stat.ST_MODE]):
                        os.chmod(pp,stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH)
 
        for dir in [f for f in dirs]:
                pp=os.path.join(root, dir).replace("""\\""",'/')
                print pp
                if stat.S_ISDIR(os.stat(pp)[stat.ST_MODE]):
                        os.chmod(pp,stat.S_IRWXU|stat.S_IWUSR|stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH)
                elif stat.S_ISREG(os.stat(pp)[stat.ST_MODE]):
                        os.chmod(pp,stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH)