Tuesday 12 June 2012

How to reset folder permissions to their default in Ubuntu/Debian

If by mistake you've ran something like:
sudo chmod / 777 -R
or similar and broken your permissions, It is possible to come back from such a messy situation, without reinstalling the system.

One way is to install another machine or VM with the same version of the OS and on that machine run this two commands:
find / -exec stat --format "chmod %a %n" {} \; > /tmp/restoreperms.sh
find / -exec stat --format 'chown %U:%G %n' {} \; >> /tmp/restoreperms.sh
Or this one that combines both:
/usr/bin/find / -exec /usr/bin/stat --format="[ ! -L {} ] && /bin/chmod %a %n" {} \; -exec /usr/bin/stat --format="/bin/chown -h %U:%G %n" {} \; > /tmp/restoreperms.sh
then, copy the /tmp/restoreperms.sh file to the machine with broken permissions:
scp /tmp/restoreperms.sh user@ip_address:/tmp/
and execute it from there.

Another way is to use the info from the deb packages and a script, but for that you'll have to have the deb packages in your machine, usualy they can be found in /var/cache/apt/archives/. This way you don't need a second machine.

The script:
#!/bin/bash
# Restores file permissions for all files on a debian system for which .deb
# packages exist.
#
# Author: Larry Kagan <me at larrykagan dot com>
# Since 2007-02-20
ARCHIVE_DIR=/var/cache/apt/archives/
PACKAGES=`ls $ARCHIVE_DIR`
cd /
function changePerms()
{
CHOWN="/bin/chown"
CHMOD="/bin/chmod"
#PERMS=$1
PERMS=`echo $1 | sed -e 's/--x/1/g' -e 's/-w-/2/g' -e 's/-wx/3/g' -e 's/r--/4/g' -e 's/r-x/5/g' -e 's/rw-/6/g' -e 's/rwx/7/g' -e 's/---/0/g'`
PERMS=`echo ${PERMS:1}`
OWN=`echo $2 | /usr/bin/tr '/' '.'`
PATHNAME=$3
PATHNAME=`echo ${PATHNAME:1}`
echo -e "CHOWN: $CHOWN $OWN $PATHNAME"
result=`$CHOWN $OWN $PATHNAME`
if [ $? -ne 0 ]; then
echo -e $result
fi
echo -e "CHMOD: $CHMOD $PERMS $PATHNAME"
result=`$CHMOD $PERMS $PATHNAME`
if [ $? -ne 0 ]; then
echo -e $result
fi
}
for PACKAGE in $PACKAGES;
do
if [ -d $PACKAGE ]; then
continue;
fi
echo -e "Getting information for $PACKAGE\n"
FILES=`/usr/bin/dpkg -c "${ARCHIVE_DIR}${PACKAGE}"`
for FILE in "$FILES";
do
#FILE_DETAILS=`echo "$FILE" | awk '{print $1"\t"$2"\t"$6}'`
echo "$FILE" | awk '{print $1"\t"$2"\t"$6}' | while read line;
do
changePerms $line
done
#changePerms $FILE_DETAILS
done
done
If that doesn't work you can try to reinstall every installed package with this script:
#!/bin/bash
for pkg in `dpkg --get-selections | egrep -v deinstall | awk '{print $1}' | egrep -v '(dpkg|apt|mysql|mythtv)'` ; do apt-get -y install --reinstall $pkg ; done
Or with:
dpkg --get-selections \* | awk '{print $1}' | xargs -r -l1 aptitude reinstall
Which does the same.



Possibly Related Posts

1 comment:

  1. i succussfuly done this,but after that i cant login as super user using su

    ReplyDelete