From 4470b39829dc41ec23e1e96a550a2278a5eea855 Mon Sep 17 00:00:00 2001 From: Jun Aishima Date: Fri, 3 Jun 2022 14:15:52 -0400 Subject: [PATCH] add utilities for running commands and folder permission checking * from py4xs.utils and lix_profile_collection/03-security, respectively --- nslsii/utils.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 nslsii/utils.py diff --git a/nslsii/utils.py b/nslsii/utils.py new file mode 100644 index 00000000..c07f1da3 --- /dev/null +++ b/nslsii/utils.py @@ -0,0 +1,40 @@ +import os +import re +import subprocess + + +def run(cmd, path="", ignoreErrors=True, returnError=False, debug=False): + """cmd should be a list, e.g. ["ls", "-lh"] + path is for the cmd, not the same as cwd + """ + cmd[0] = path + cmd[0] + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = p.communicate() + if debug: + print(out.decode(), err.decode()) + if len(err) > 0 and not ignoreErrors: + print(err.decode()) + raise Exception(err.decode()) + if returnError: + return out.decode(), err.decode() + else: + return out.decode() + + +def check_access(fn): + if not os.path.exists(fn): + raise Exception(f"{fn} does not exist ...") + if os.access(fn, os.W_OK): + print(f"write access to {fn} verified ...") + return + + # this below may not be necessary + out = run(["getfacl", "-cn", fn]) + wgrps = [int(t[:-4].lstrip("group:")) for t in re.findall("groups:[0-9]*:rw.", out)] + ugrps = os.getgroups() + if len(set(wgrps) & set(ugrps)) == 0: + print("groups with write permission: ", wgrps) + print("user group membership: ", ugrps) + raise Exception(f"the current user does not have write access to {fn}") + else: + print(f"write access to {fn} verified ...")