python - linux 目录权限检查和/或 dir 是否存在

标签 python linux root su

我有一个脚本,它在 Linux 上以 ROOT 身​​份运行,收集来自不同用户的数据。给定每个用户的 nfs 路径 1) 验证主管不存在 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 的值

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

一旦永久拒绝或没有为用户确认此类文件,则需要执行某些操作。
/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 "$1"

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

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

关于python - linux 目录权限检查和/或 dir 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68736288/

相关文章:

python - Flask 应用程序崩溃“正在使用重新加载程序重新启动....socket.error : [Errno 98] Address already in use

linux - 更改 dot.profile 和 .bashrc

c - 绑定(bind)失败: Address already in use

linux - Shell 历史中的可疑命令

python - 使用 Flask 显示 stackOverflow API JSON 数据

python - 检查字典中的多个键

linux - unrar : error while loading shared libraries: libstdc++. so.6:无法打开共享对象文件:没有这样的文件或目录

linux - 成为 root 的 Shell 脚本?

用户 'odbc' @'localhost' 对数据库的 mysql 访问被拒绝

python - 如何从 Keras 中的 ImageDataGenerator 格式化 X 和 Y 数据?