在 python 脚本中更改为 sudo 用户 [英] Change to sudo user within a python script

查看:41
本文介绍了在 python 脚本中更改为 sudo 用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题.我正在编写一个软件,它需要执行需要用户处于 sudo 模式的操作.运行 'sudo python filename.py' 不是一个选项,这让我想到了我的问题.有没有办法在python脚本中途更改为sudo,安全性不是问题,因为用户会知道程序应以以下方式运行的sudo密码来说明问题

I have a problem. I am writing a piece of software, which is required to perform an operation which requires the user to be in sudo mode. running 'sudo python filename.py' isn't an option, which leads me to my question. Is there a way of changing to sudo half way through a python script, security isn't an issue as the user will know the sudo password the program should run in the following way to illustrate the issue

  1. 以普通用户身份运行的程序
  2. ......执行操作
  3. 用户输入 sudo 密码
  4. 用户已更改为 sudo
  5. 运行需要 sudo 权限的子程序
  6. 触发偶数(子程序结束)用户再次成为普通用户
  7. ......执行操作

我的问题在于第 3 步,您可以建议的任何指针或框架都会有很大帮助.

My problem lies in step 3, any pointers or frameworks you could suggest would be of great help.

干杯

克里斯

推荐答案

使用 Tcl 和 Expect,加上子流程来提升自己.所以基本上是这样的:

Use Tcl and Expect, plus subprocess to elevate yourself. So basically it's like this:

sudo.tcl

spawn sudo
expect {
    "Password:" {
        send "password"
    }
}

sudo.py

import subprocess
subprocess.call(['tclsh', 'sudo.tcl'])

然后运行 ​​sudo.py.

And then run sudo.py.

这篇关于在 python 脚本中更改为 sudo 用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆