programing

파일에서 Unix 권한 마스크를 어떻게 얻을 수 있습니까?

projobs 2021. 1. 17. 10:24
반응형

파일에서 Unix 권한 마스크를 어떻게 얻을 수 있습니까?


파이썬을 사용하여 * nix에서 644 또는 755와 같은 파일의 권한 마스크를 어떻게 얻을 수 있습니까?

이를 수행하는 기능이나 클래스가 있습니까? 대단히 감사합니다!


os.statstat (2) 시스템 호출 인터페이스를 둘러싼 래퍼 입니다.

>>> import os
>>> from stat import *
>>> os.stat("test.txt") # returns 10-tupel, you really want the 0th element ...
posix.stat_result(st_mode=33188, st_ino=57197013, \
    st_dev=234881026L, st_nlink=1, st_uid=501, st_gid=20, st_size=0, \
    st_atime=1300354697, st_mtime=1300354697, st_ctime=1300354697)

>>> os.stat("test.txt")[ST_MODE] # this is an int, but we like octal ...
33188

>>> oct(os.stat("test.txt")[ST_MODE])
'0100644'

여기에서 일반적인 8 진 권한을 알 수 있습니다.

S_IRWXU 00700   mask for file owner permissions
S_IRUSR 00400   owner has read permission
S_IWUSR 00200   owner has write permission
S_IXUSR 00100   owner has execute permission
S_IRWXG 00070   mask for group permissions
S_IRGRP 00040   group has read permission
S_IWGRP 00020   group has write permission
S_IXGRP 00010   group has execute permission
S_IRWXO 00007   mask for permissions for others (not in group)
S_IROTH 00004   others have read permission
S_IWOTH 00002   others have write permission
S_IXOTH 00001   others have execute permission

당신은 정말로 낮은 비트 에만 관심이 있으므로 나머지는 잘라낼 수 있습니다.

>>> oct(os.stat("test.txt")[ST_MODE])[-3:]
'644'
>>> # or better
>>> oct(os.stat("test.txt").st_mode & 0o777)

참고 : 위쪽 부분은 파일 형식을 결정합니다. 예 :

S_IFMT  0170000 bitmask for the file type bitfields
S_IFSOCK    0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 regular file
S_IFBLK 0060000 block device
S_IFDIR 0040000 directory
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO
S_ISUID 0004000 set UID bit
S_ISGID 0002000 set-group-ID bit (see below)
S_ISVTX 0001000 sticky bit (see below)

나는 이것이 파일의 권한 비트를 얻는 가장 명확한 방법이라고 생각합니다.

stat.S_IMODE(os.lstat("file").st_mode)

os.lstat 함수는 파일이 심볼릭 링크 인 경우 링크 자체의 모드를 제공하는 반면 os.stat는 링크를 역 참조합니다. 따라서 os.lstat가 가장 일반적으로 유용하다고 생각합니다.

다음은 정규 파일 "testfile"과 후자 "testlink"에 대한 심볼릭 링크가있는 경우의 예입니다.

import stat
import os

print oct(stat.S_IMODE(os.lstat("testlink").st_mode))
print oct(stat.S_IMODE(os.stat("testlink").st_mode))

이 스크립트는 나를 위해 다음을 출력합니다.

0777
0666

stat의 의미를 파악하고 싶지 않은 경우이를 수행하는 또 다른 방법은 os.access 명령 http://docs.python.org/library/os.html#os.access 를 사용하는 것입니다. 그러나 가능한 문서를 읽어보십시오. 보안 문제들

예를 들어 읽기 / 쓰기 권한이있는 test.dat 파일에 대한 권한을 확인하려면

os.access("test.dat",os.R_OK)
>>> True

#Execute permissions
os.access("test.dat",os.X_OK)
>>> False

#And Combinations thereof
os.access("test.dat",os.R_OK or os.X_OK)
>>> True

os.access("test.dat",os.R_OK and os.X_OK)
>>> False

oct (os.stat ( '파일') .st_mode) [4 :]


확실히 os 모듈 안에는 많은 파일 기반 함수가 있습니다. 당신이 실행하는 경우 os.stat(filename)당신은 항상 결과를 interprate 수 있습니다.

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


os.stat는 c-lib stat와 유사합니다 (리눅스에서는 man 2 stat에서 정보를 확인).

stats = os.stat('file.txt')
print stats.st_mode

os.access(path, mode) method returns True if access is allowed on path, False if not.

available modes are :

  1. os.F_OK - test the existence of path.
  2. os.R_OK - test the readability of path.
  3. os.W_OK - test the writability of path.
  4. os.X_OK - test if path can be executed.

for example, checking file /tmp/test.sh has execute permission

ls -l /tmp/temp.sh
-rw-r--r--  1 *  *  0 Mar  2 12:05 /tmp/temp.sh

os.access('/tmp/temp.sh',os.X_OK)
False

after changing the file permission to +x 
chmod +x /tmp/temp.sh

ls -l /tmp/temp.sh
-rwxr-xr-x  1 *  *  0 Mar  2 12:05 /tmp/temp.sh

os.access('/tmp/temp.sh',os.X_OK)
True

You can just run a Bash stat command with Popen if you want:

The normal Bash command:

jlc@server:~/NetBeansProjects/LineReverse$ stat -c '%A %a %n' revline.c
-rw-rw-r-- 664 revline.c

And then with Python:

>>> from subprocess import Popen, PIPE
>>> fname = 'revline.c'
>>> cmd = "stat -c '%A %a %n' " + fname
>>> out = Popen(cmd, shell=True, stdout=PIPE).communicate()[0].split()[1].decode()
>>> out
'664'

And here's another way if you feel like searching the directory:

>>> from os import popen
>>> cmd = "stat -c '%A %a %n' *"
>>> fname = 'revline.c'
>>> for i in popen(cmd):
...     p, m, n = i.split()
...     if n != fname:
...         continue
...     print(m)
        break
... 
664
>>> 

ReferenceURL : https://stackoverflow.com/questions/5337070/how-can-i-get-the-unix-permission-mask-from-a-file

반응형