linux目录权限检查and/or目录是否存在

linux directory permission check and/or dir exist or not

我有一个脚本 运行 作为 linux 的 ROOT 从不同用户收集数据。给定每个用户的 nfs 路径 1) 验证 director 不存在 2) 验证权限被拒绝

verify_model_path_not_found = '/usr/bin/su ' + userID + ' -c \'/usr/bin/ls ' +  u_model_path + '  | /usr/bin/grep \"Permission denied\|No such file or directory\"\''
perm_denied_str = 'Permission denied'
no_file_dir_str =  'No such file or directory'

print("verify_model_path_not_found:", verify_model_path_not_found)

#Run as a root
try:
    verify_cmd_out = subprocess.check_output(verify_model_path_not_found, shell=True) 
    verify_cmd_out = str(verify_cmd_out)
    print("verify_cmd_out:", verify_cmd_out, "\n")

except subprocess.CalledProcessError as errorcatch:
    print(datetime.datetime.now(), " Error while executing ", verify_model_path_not_found)
    print("error code", errorcatch.returncode, errorcatch.output, "\n")
    continue 

#only add items that are not accessible (perm denied or no file found)
if  ((perm_denied_str in verify_cmd_out) or (no_file_dir_str in verify_cmd_out)):
    #remaining actions .... send an email to the user ...

示例输出错误:

verify_model_path_not_found: /usr/bin/su xxxx  -c '/usr/bin/ls /nfs/x/y/z  | /usr/bin/grep "Permission denied\|No such file or directory"'
2021-08-10 17:00:31.827186  Error while executing  /usr/bin/su xxxx -c '/usr/bin/ls /nfs/x/y/z | /usr/bin/grep "Permission denied\|No such file or directory"'
error code 1 b''  #I know this dir does not exist or perm denied - still getting error 

鉴于 /nfs/x/y/z,如果用户没有读取权限,我想使用 grep 获得“权限被拒绝”-“权限被拒绝”应该是 verify_cmd_out[= 的值14=]

给定 /nfs/x/y/z,如果目录不存在,我想使用 grep 获取“没有这样的文件或目录” - “没有这样的文件或目录”应该是 [=28= 的值]

一旦 perm 被拒绝或没有为用户确认此类文件,则需要执行某些操作。
/usr/bin/su xxxx -c ... 命令无法正常工作,有什么想法或想法可以解决这个问题吗?

您正在检查标准输出(文件描述符 1),但错误消息(以及一般的进度和诊断)发布在标准错误(文件描述符 2)上。

反正你的代码很笨拙。可能会尝试一些类似

的方法
import subprocess

def assert_error_stderr(cmd, expected_stderr):
    """
    Accept a shell command; verify that it fails with error,
    and emits the expected message on standard error.
    """
    try:
        result = subprocess.run(cmd, check=True, text=True, capture_output=True)
        raise ValueError("%r did not raise an error" % cmd)
    except CalledProcessError:
        assert expected_stderr in result.stderr

def assert_silent_failure(cmd):
    """
    Check that a command fails; verify that standard error is empty
    """
    try:
        result = subprocess.run(cmd, check=True, text=True, capture_output=True)
    except CalledProcessError:
        assert result.stderr == ''
    raise ValueError("%r did not fail", cmd)

assert_silent_failure(['su', '-c' 'test -d ' + u_model_path])
...

当然,当您从根本上想测试 shell 时使用 Python 可能没有多大意义。

#!/bin/sh
! test -d ""

基本上 never use ls in scripts 并且通常可能不依赖于特定的错误消息(它可以本地化,或者在版本之间更改)。

此外,在 Python subprocess 代码中,尽可能避免 shell=True。另见 Actual meaning of shell=True in subprocess