使用subprocess.call时如何键入sudo密码? [英] how to type sudo password when using subprocess.call?

查看:423
本文介绍了使用subprocess.call时如何键入sudo密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个函数,该函数不时切换我的代理设置,
的问题是我希望它在没有人工干预的情况下循环运行。但是,当我在sudo中执行程序时,它会在第一次顺利运行时被调用,第二次它会要求我提供sudo密码。这是代码的一部分:

i defined a function that switch my proxy settings every now and then, problem is that i want it to run in a loop without manual intervention. But when i execute the program in sudo it gets called the first time en runs smoothly, second time it asks me for my sudo password. Here is the bit of code:

def ProxySetting(Proxy):
    print "ProxyStetting(Proxy)"
    call("networksetup -setwebproxy 'Wi-Fi' %s" "on" % Proxy, shell = True)
    call("networksetup -setsecurewebproxy 'Wi-Fi' %s" "on" % Proxy, shell = True)
    call("networksetup -setftpproxy 'Wi-Fi' %s" "on" %Proxy , shell=True)

我可以使用线程,但是可以肯定有一种方法不会造成问题。我该如何对sudo密码进行硬编码,使其在功能开始时运行?

I could use threading but am sure there is a way of doing it that wont cause problems. How can i hard code my sudo password so that it runs at the beginning of the function?

推荐答案

在这里您可以执行sudo命令,而无需交互式提示,要求您输入密码:

Here you can execute a command sudo without interactive prompt asking you to type your password :

from subprocess import call    

pwd='my password'
cmd='ls'

call('echo {} | sudo -S {}'.format(pwd, cmd), shell=True)

这篇关于使用subprocess.call时如何键入sudo密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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