Created
February 6, 2017 21:16
-
-
Save beugley/47b4812df0837fc90e783347faee2432 to your computer and use it in GitHub Desktop.
Python script to convert a Linux octal permission number to a text string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def perm_to_text(perm): | |
perms = { | |
"0": "---", | |
"1": "--x", | |
"2": "-w-", | |
"3": "-wx", | |
"4": "r--", | |
"5": "r-x", | |
"6": "rw-", | |
"7": "rwx" | |
} | |
if len(perm) == 4: | |
first = perm[0] | |
perm = perm[1:] | |
else: | |
first = "" | |
try: | |
outperms = "" | |
for p in perm: | |
outperms += perms[p] | |
except KeyError as e: | |
outperms = perm | |
if first != "": | |
if first == '0': | |
pass | |
elif first == '1': | |
pass | |
elif first == '2': | |
if outperms[5] == 'x': | |
outperms = outperms[:5]+'s'+outperms[6:] | |
else: | |
outperms = outperms[:5]+'S'+outperms[6:] | |
elif first == '4': | |
if outperms[2] == 'x': | |
outperms = outperms[:2]+'s'+outperms[3:] | |
else: | |
outperms = outperms[:2]+'S'+outperms[3:] | |
else: | |
outperms = perm | |
return "-"+outperms |
Sorry, my function does exactly the reverse of the initial question... It's like the post from Justin Timperio
I have a version which handles the additional permissions like Sticky bit, Set User/Group bits. For instance, it converts 'rwsr-Sr-T'. Note that my code is extracted from my tools and allows to pass an octal value (usually a mistake). Here is the code 👍
def set_fmode(value) :
"""
Convert a 'rwsr-xr-T' format to a decimal value
"""
lvalue = len(value)
# Check if 'value' has the right format
if (isinstance(value,
str)
and not [x for x in value if x not in '-rwxXsStT']
and lvalue == 9) :
pos = lvalue - 1
res = 0
for c in value :
if c in 'sStT' :
# Special modes
res += (1 << pos // 3) << 9
res += 1 << pos if c in 'rwxst' else 0
pos -= 1
elif isinstance(value,
int) :
res = value
else :
raise ValueError
return res
import stat
stat.filemode(0o107664) # '-rwSrwSr-T'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for writing and posting this! This was very helpful in writing my own parser. If you need to convert from symbolic to numeric you can use this function.
This will convert input like '-rw-r--r--' to '644'