Tuesday, October 15, 2013

File permissions list in Python

Python script file permissions list


In this small blog I will demonstrate a easy way to show listed file permissions in a Linux Distro environment. This simple script written in Python language, will use the find command under the linux shell and display results with the permissions assigned to a particular file.
Now let us take a look at the code:

<<<CODE>>>
import stat, sys, os, string, commands
#try block with a search pattern 
try:
    #run a 'find' command and assign results to a variable
    pattern = raw_input("Enter the file pattern to search for:\n")
    commandString = "find " + pattern
    commandOutput = commands.getoutput(commandString)
    findResults = string.split(commandOutput, "\n")

    #output find results, along with permissions
    print "Files:"
    print commandOutput
    print "================================"
    for file in findResults:
        mode=stat.S_IMODE(os.lstat(file)[stat.ST_MODE])
        print "\nPermissions for file ", file, ":"
        for level in "USR", "GRP", "OTH":
            for perm in "R", "W", "X":
                if mode & getattr(stat,"S_I"+perm+level):
                    print level, " has ", perm, " permission"
                else:
                    print level, " does NOT have ", perm, " permission"
except:
    print "There was a problem - check the message above"

<<</CODE>>>


Now you can take your favorite Linux text editor and save this code under a "check_F.py" file. I have created three files with different permissions to demonstrate how this script work.


As we can see there are 3 files: test01.txt, test02.tiff and test03.cdr. Now to display the list of file permissions for these file we have to run the check_F.py script. This can be achieved under the shell using the following syntax:  "python check_F.py". Next thing we can do is to type a beginning of the file name with a star sign  "t*". Then we can look at the output.



And we get a fine table output with user, group and everyone permission defined for each file. These files are listed under the current folder, but everyone can choose any other folder using the default find syntax "/etc/t*"

This is all for now. 

Feel free to comment.

No comments:

Post a Comment