如何在Python中使用sudo权限编写文件?

问题描述 投票:0回答:4

我想用python将内容写入文件。该文件的位置位于根目录路径:/etc/hosts

以下是文件权限

-rw-r--r--  1 root root

我想更新这个文件,它只能用sudo更新。所以我写了以下脚本:

path = "/etc/hosts"
fr = open(path,'r')
b = fr.read()
b = b+'something to write'
fr.close()
fw = open(path,'w')
fw = os.system('echo %s|sudo -S python %s' % ('root', fw.write(b)))

但是我得到了许可被拒绝的错误:

IOError:[Errno 13]权限被拒绝:你'/ etc / hosts'

我也尝试过子进程:

os.popen("sudo -S %s"%(open(path,'w')), 'w').write(admin_password)

但这再次没有奏效。

我该如何解决这个问题?

python file subprocess sudo
4个回答
-1
投票

检查/ etc / hosts文件夹权限或文件权限


-1
投票

以下解决方案最终为我工作。我创建了一个名为etcedit.py的新文件,它将写入该文件。

os.system("echo %s| sudo -S python etcedit.py %s"  % ('rootpassword', 'host_name'))

我的etcedit.py文件

import os, subprocess
import sys
from sys import argv

def etc_update(host_name, *args):
    path = "/etc/hosts"
    host_name = host_name[0]
    fw = open(path,'w')
    fw.write(host_name)

etc_update(sys.argv[1:])

这有效!


-1
投票

如果没有权限,您可以使用sudo重新运行脚本。需要pexpect模块。

例如:

import os
import pexpect
import sys
import argparse

def get_args():
    parser = argparse.ArgumentParser(description="Run as sudo!")
    parser.add_argument('-p', dest='privelege', action='store', help='also has rights')
    args = parser.parse_args()
    return vars(args)

full_path = os.path.abspath(__file__)
print("full_path = %s", full_path)

if __name__ == '__main__':
    args = get_args()
    if args.get('privelege') == None:
        #check if it has sudo privelege and if not rerun with it.
        child = pexpect.spawn("sh", logfile = sys.stdout)
        child.sendline("sudo python %s  -p root" % full_path)
        child.expect("assword", timeout = 100)
        child.logfile = None
        child.sendline("YOUR_PASSWORD")
        child.logfile_read = sys.stdout
    elif args.get('privelege') == 'root':
        #if it have root privelege do action
        path = "/etc/hosts"
        fr = open(path,'r')
        b = fr.read()
        b = b+'something to write'
        fr.close()
        fw = open(path,'w')
        fw.write(b)
        fw.close()

如果脚本没有root privelege,则运行sh而不是使用sudo重新运行self。

© www.soinside.com 2019 - 2024. All rights reserved.