【问题标题】:How to write a file with sudo privileges in Python?如何在 Python 中编写具有 sudo 权限的文件?
【发布时间】:2019-09-03 04:49:00
【问题描述】:

我想用 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] Permission denied: u'/etc/hosts'

我也尝试过使用子进程:

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

但这又没用。

我该如何解决这个问题?

【问题讨论】:

  • 你应该像sudo python myscript.py一样使用sudo运行python脚本
  • 您在尝试阅读时已经收到权限错误。
  • 我的整个代码都在同一个文件中,我没有用终端执行这个:)
  • @Dschoni 没有文件读取成功但没有写入。

标签: python file subprocess sudo


【解决方案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 权限,则运行 sh,然后使用 sudo 重新运行 self。

【讨论】:

    【解决方案2】:

    以下解决方案最终对我有用。我创建了一个名为 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:])
    

    这行得通!

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 问题中已给出。如果您没有看到它,这应该是一条评论
      • 我需要 sudo 权限才能写入该文件,这就是我添加 os.system('echo %s|sudo -S python %s' % ('root', fw.write(b))) 的原因
      猜你喜欢
      • 2011-08-03
      • 2013-07-11
      • 2012-11-12
      • 2018-10-24
      • 2012-06-10
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多