![](/img/trans.png)
[英]check if the file exist if not create new dir and create file inside the dir and return the file inside the dir
[英]linux directory permission check and/or dir exist or not
我有一个脚本,它在 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的值
一旦为用户确认 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 "$1"
基本上从不在脚本中使用ls
并且通常可能不依赖于特定的错误消息(它可以是本地化的,或者在版本之间发生变化)。
此外,在 Python subprocess
代码中,尽可能避免shell=True
。 另请参阅子进程中shell=True
实际含义
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.