Bootstrap FreeKB - Python (Scripting) - Determine file or directory owner
Python (Scripting) - Determine file or directory owner

Updated:   |  Python (Scripting) articles

getpwuid and stat can be used to determine the user that owns a file or directory.

#!/usr/bin/python3
from os import stat
from pwd import getpwuid

owner = getpwuid(stat("/tmp/foo.txt").st_uid).pw_name

print(f"owner = {owner}")

 

Something like this should be returned.

owner = john.doe

 

Or better yet, as a function.

#!/usr/bin/python3
from os import stat
from pwd import getpwuid

def return_owner(object):
  return getpwuid(stat(object).st_uid).pw_name

owner = return_owner("/tmp/foo.txt")

print(f"owner = {owner}")

 

Better yet, let's check to see if the file or directory exists.

#!/usr/bin/python3
import os
import re
from os import stat
from pwd import getpwuid

def return_owner(object):
  if os.path.exists(object):
    return getpwuid(stat(object).st_uid).pw_name
  else:
    return str(object)+" does not exist"

objects = ['/tmp', '/tmp/foo.txt', '/tmp/bar.txt']

for object in objects:
  owner = return_owner(object)
  if re.match('.*does not exist.*', owner):
    print(owner)
  else:
    print(f"{object} is owned by {owner}")

 

Something like this should be returned.

/tmp is owned by root
/tmp/foo.txt is owned by john.doe
/tmp/bar.txt does not exist

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 2437a4 in the box below so that we can be sure you are a human.