在 Python 脚本中使用 sudo [英] Using sudo with Python script

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

问题描述

每次执行脚本时,我都在尝试编写一个小脚本来挂载 VirtualBox 共享文件夹.我想用 Python 来做这件事,因为我正在努力学习它来编写脚本.

I'm trying to write a small script to mount a VirtualBox shared folder each time I execute the script. I want to do it with Python, because I'm trying to learn it for scripting.

问题是我需要特权才能启动 mount 命令.我可以将脚本作为 sudo 运行,但我更喜欢它自己制作 sudo.

The problem is that I need privileges to launch mount command. I could run the script as sudo, but I prefer it to make sudo by its own.

我已经知道将您的密码写入 .py 文件是不安全的,但我们讨论的是一个根本不重要的虚拟机:我只想单击 .py 脚本并使其工作.

I already know that it is not safe to write your password into a .py file, but we are talking about a virtual machine that is not critical at all: I just want to click the .py script and get it working.

这是我的尝试:

#!/usr/bin/env python
import subprocess

sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'

subprocess.Popen('sudo -S' , shell=True,stdout=subprocess.PIPE)
subprocess.Popen(sudoPassword , shell=True,stdout=subprocess.PIPE)
subprocess.Popen(command , shell=True,stdout=subprocess.PIPE)

我的python版本是2.6

My python version is 2.6

推荐答案

sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'
p = os.system('echo %s|sudo -S %s' % (sudoPassword, command))

试试这个,让我知道它是否有效.:-)

Try this and let me know if it works. :-)

还有这个:

os.popen("sudo -S %s"%(command), 'w').write('mypass')

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

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