How to Get the Owner and Group of a Folder with Python on a Linux MAChine

How to get the owner and group of a folder with Python on a Linux machine?

Use os.stat() to get the uid and gid of the file. Then, use pwd.getpwuid() and grp.getgrgid() to get the user and group names respectively.

import grp
import pwd
import os

stat_info = os.stat('/path')
uid = stat_info.st_uid
gid = stat_info.st_gid
print uid, gid

user = pwd.getpwuid(uid)[0]
group = grp.getgrgid(gid)[0]
print user, group

How to get the group of a folder with Python on a Linux?

/sys/class/gpio/gpio252 is a symlink to a different file and python returns the information from the file and not the symlink.

check the group of:

ls -ld /sys/devices/6000d000.gpio/gpiochip0/gpio/gpio252

how to find the owner of a file or directory in python

I'm not really much of a python guy, but I was able to whip this up:

from os import stat
from pwd import getpwuid

def find_owner(filename):
return getpwuid(stat(filename).st_uid).pw_name

Python - list files that belong to specific 'group'

this may work:

import os
import grp
gid = grp.getgrnam('foo').gr_gid

file_list = []
for fle in os.listdir('dir'):
if os.stat(fle).st_gid == gid:
file_list.append(fle)

or as a one-liner (list-comprehension):

file_list = [fle for fle in os.listdir('dir') if os.stat(fle).st_gid == gid]

How to change the user and group permissions for a directory, by name?

import pwd
import grp
import os

uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid
path = '/tmp/f.txt'
os.chown(path, uid, gid)

Getting owner of file from smb share, by using python on linux

This was unbelievably not a trivial task, and unfortunately the answer isn't simple as I hoped it would be..

I'm posting this answer if someone will be stuck with this same problem in the future, but hope maybe someone would post a better solution earlier

In order to find the owner I used this library with its examples:

from smb.SMBConnection import SMBConnection

conn = SMBConnection(username='<username>', password='<password>', domain=<domain>', my_name='<some pc name>', remote_name='<server name>')
conn.connect('<server name>')

sec_att = conn.getSecurity('<share name>', r'\some\file\path')
owner_sid = sec_att.owner

The problem is that pysmb package will only give you the owner's SID and not his name.

In order to get his name you need to make an ldap query like in this answer (reposting the code):

from ldap3 import Server, Connection, ALL
from ldap3.utils.conv import escape_bytes

s = Server('my_server', get_info=ALL)
c = Connection(s, 'my_user', 'my_password')
c.bind()

binary_sid = b'....' # your sid must be in binary format

c.search('my_base', '(objectsid=' + escape_bytes(binary_sid) + ')', attributes=['objectsid', 'samaccountname'])
print(c.entries)

But of course nothing will be easy, it took me hours to find a way to convert a string SID to binary SID in python, and in the end this solved it:

# posting the needed functions and omitting the class part
def byte(strsid):
'''
Convert a SID into bytes
strdsid - SID to convert into bytes
'''
sid = str.split(strsid, '-')
ret = bytearray()
sid.remove('S')
for i in range(len(sid)):
sid[i] = int(sid[i])
sid.insert(1, len(sid)-2)
ret += longToByte(sid[0], size=1)
ret += longToByte(sid[1], size=1)
ret += longToByte(sid[2], False, 6)
for i in range(3, len(sid)):
ret += cls.longToByte(sid[i])
return ret

def byteToLong(byte, little_endian=True):
'''
Convert bytes into a Python integer
byte - bytes to convert
little_endian - True (default) or False for little or big endian
'''
if len(byte) > 8:
raise Exception('Bytes too long. Needs to be <= 8 or 64bit')
else:
if little_endian:
a = byte.ljust(8, b'\x00')
return struct.unpack('<q', a)[0]
else:
a = byte.rjust(8, b'\x00')
return struct.unpack('>q', a)[0]

... AND finally you have the full solution! enjoy :(

What is a cross-platform way to get the home directory?

You want to use os.path.expanduser.

This will ensure it works on all platforms:

from os.path import expanduser
home = expanduser("~")

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())

How to set a files owner in python?

os.chown(path, uid, gid)

http://docs.python.org/library/os.html

The uid and gid can be retrieved from a string by

import pwd
import grp
import os

uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid

Reference: How to change the user and group permissions for a directory, by name?

How to find file owners that have one file in a directory but don't have another

It doesn't look like samantha.foo is owned by samantha in the sense of Linux file ownership. The ownership here seems to be within your application. If your filenames contain the owner name, you can try something like:

# Get all files with extensions foo and bar
foos=(*.foo)
bars=(*.bar)
# Strip the extensions to get the usernames
users_with_foo=("${foos[@]%.foo}")
users_with_bar=("${bars[@]%.bar}")
# Filter the usernames.
grep -vxf <(printf "%s\n" "${users_with_bar[@]}") <(printf "%s\n" "${users_with_foo[@]}")

With grep, -v prints lines that don't match any patterns, -x looks for exact matches (the whole line must match the pattern) and -f is used to read patterns from an input file. Here, the "files" are from process substitution (<(...)). So the printf commands' output are provided as files to grep, which it uses as files for patterns and input.



Related Topics



Leave a reply



Submit