Archive for March 19th, 2009

Fixing messed up permissions on a linux filesystem

No Comments »

Ever accidentally change permissions on a filesystem and don’t know what it was before or how to get it back? Me too…

I was messing around with openSuSE the other day. I installed it on another partition on my hard drive. I mounted my Ubuntu partition and was just trying to copying some stuff over. In one of my dumbest moves I did something to the effect of chmod a+rwx /media/ubuntu, effectively screwing up all my permissions…I honestly don’t know what I was thinking.

Just recently I booted into my Ubuntu installation and noticed something weird when I logged it. It said that it couldn’t read some .dmrc file because of wrong permissions. I just fixed the problem and carried on. Then as I was trying to run a command with sudo it gave me the same error, that the permissions on /etc/sudoers was wrong. Good luck fixing that without a root password.

So I went back to openSuSE and wrote a little script that would fix the permissions as much as possible. I had another Ubuntu system that I mounted using sshfs and then basically searched for every file that existed locally on the remote machine and took the permissions from the remote machine’s files and copied them locally to fix the issue. Obviously it would not catch every file because I have different things installed on each but since they were both Ubuntu machines it came out close enough.

So here is the script I used, hopefully it will be of help:


#/usr/bin/env python
import os, stat, sys

def get_perms(path):
	st = os.stat(path)
	mode = st[stat.ST_MODE]
	return mode & 07777

def set_perms(frompath, topath):
	os.chmod(topath, get_perms(frompath))

if __name__ == "__main__":
	print "copying perms to %s" % sys.argv[1]
	print "looking for similar files in %s" % sys.argv[2]
	if raw_input("do you wish to continue? ").lower() == "y":
		for root, dirs, files in os.walk(sys.argv[1]):
			for f in files+dirs:
				topath = os.path.join(root, f)
				frompath = topath.replace(sys.argv[1], sys.argv[2], 1)
				print "doing %s -> %s" % (frompath, topath)
				if os.path.islink(topath):
					print "file %s is a link, skipping" % topath
					continue
				if not os.path.exists(frompath):
					print "file %s does not exist to copy perms from" % frompath
					continue

				#print "frompath %s, perms %o" % (frompath, get_perms(frompath))
				#print "topath before to %s, perms %o" % (topath, get_perms(topath))

				set_perms(frompath, topath)
				#print "frompath %s, perms %o" % (frompath, get_perms(frompath))
				#print "topath after to %s, perms %o" % (topath, get_perms(topath))