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

2024-06-25 06:08:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在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")

这是错误

^{pr2}$

Tags: 方法脚本bashlogvaras错误root
1条回答
网友
1楼 · 发布于 2024-06-25 06:08:51

{{cd2>处理^不是可执行文件。在尝试使用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-脚本的方法是这样调用它,只需删除chmod

^{pr2}$

实际上,如果我们可以假设bashPATH上,那么这将更便于移植:

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

相关问题 更多 >