gpt4 book ai didi

python - 尝试在子进程中调用 bash 脚本时,我被拒绝了权限

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:47 26 4
gpt4 key购买 nike

我正在尝试在我的 python 脚本中运行 bash 脚本,我确信有一种方法可以代替我的 bash 脚本在 python 中执行的操作,但我更专注于让它工作。

这是我以 root 身份运行的代码,后面是错误:

import subprocess
#variable = subprocess.check_output('dmidecode', shell=True)
#print(variable)
#run program once as root then cron it as root
try :
file = open("/var/log/serialcontrol/dmidecode.txt", "r")
except FileNotFoundError:
file = open('/var/tmp/serialcontrol.bash', 'w')
file.write("#!/bin/bash/\nif [ ! -d /var/log/serialcontrol/]\nthen\n\tmkdir /var/log/serialcontrol/\nfi");
file.close()
subprocess.call("/var/tmp/serialcontrol.bash")

这里是错误

Traceback (most recent call last):
File "/home/trisimix/serialcontrol/serialcontrol.py", line 6, in <module>
file = open("/var/log/serialcontrol/dmidecode.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: '/var/log/serialcontrol/dmidecode.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/trisimix/serialcontrol/serialcontrol.py", line 11, in <module>
subprocess.call("/var/tmp/serialcontrol.bash")
File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
PermissionError: [Errno 13] Permission denied

最佳答案

您在处理 FileNotFoundError 时创建的 /var/tmp/serialcontrol.bash 文件不可执行。在尝试使用 subprocess 执行它之前先使其可执行。

import subprocess
import os
import stat

#variable = subprocess.check_output('dmidecode', shell=True)
#print(variable)
#run program once as root then cron it as root
try :
file = open("/var/log/serialcontrol/dmidecode.txt", "r")
except FileNotFoundError:
script = '/var/tmp/serialcontrol.bash'
with open(script, 'w') as file:
file.write("#!/usr/bin/env bash/\nif [ ! -d /var/log/serialcontrol/]\nthen\n\tmkdir /var/log/serialcontrol/\nfi");

st = os.stat(script)
os.chmod(script, st.st_mode | stat.S_IEXEC)

subprocess.call(script)

作为@anishsane在评论中指出,chmod-ing 脚本的另一种替代方法是像这样调用它,然后删除 chmod:

subprocess.call(["/bin/bash", script])

实际上,如果我们可以假设 bashPATH 上,那么这会更便携:

subprocess.call(["bash", script])

关于python - 尝试在子进程中调用 bash 脚本时,我被拒绝了权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41296786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com