在python中杀死sudo启动的子进程 [英] Killing sudo-started subprocess in python
问题描述
我与一个可以进行根级调用而无需提供密码的用户一起运行.我的用户当前正在执行类似操作
I am running with a user that can make root-level calls without having to supply a password. My user currently does something like this
pr = subprocess.Popen("sudo sleep 100".split())
sleep(5)
pr.kill()
但这会导致此错误,因为用户不是root用户,因此无法杀死root用户进程
but that leads to this error because the user isn't root so it can't kill a root process
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 1572, in kill
self.send_signal(signal.SIGKILL)
File "/usr/lib/python2.7/subprocess.py", line 1562, in send_signal
os.kill(self.pid, sig)
OSError: [Errno 1] Operation not permitted
所以我尝试做这样的事情
so I try to do something like this
pr = subprocess.Popen("sudo sleep 100".split())
sleep(5)
kill_pr = subprocess.Popen("sudo kill {}".format(pr.pid))
但这并不会杀死有问题的进程.例如,如果
but that doesn't kill the process in question. For example, if
>> subprocess.Popen("sudo sleep 100".split()).pid
5000
但是
$ pgrep sleep
5001
所以从subprocess.Popen("..").pid
返回的pid
似乎比运行我要杀死的命令的进程的实际pid高
so it seems that the pid
returned from subprocess.Popen("..").pid
is one higher than the actual pid of the process running the command that I want to kill
我假设从Popen
调用返回的pid
是父进程,所以我尝试做类似的事情
I'm assuming that the pid
returned from the Popen
call is the parent process, so I try doing something like
sudo kill -- -$PID
,其中$PID
是从Popen
返回的那个,但这只是给我
sudo kill -- -$PID
, where $PID
is the one returned from Popen
, but that just gives me
kill: sending signal to -2100 failed: No such process
为什么不存在该进程?
本质上,我只需要一种使用python的子进程在sudo
中运行命令的方法,然后能够在需要时将其杀死.我假设我需要在要杀死的进程的pid
上运行某种类型的sudo kill
命令,或者类似的操作,但是我无法确切确定如何执行此操作.
Essentially, I just need a way to run a command with sudo
using python's subprocess, then be able to kill it when I need to. I'm assuming I need to run some type of sudo kill
command with the pid
of the process I'm trying to kill or something like that but I'm unable to determine exactly how to do this.
推荐答案
我想我明白了,问题是如果我这样做了
I think I figured it out, the issue was that if I did this
import subprocess, os
pr = subprocess.Popen(["sudo", "sleep", "100"])
print("Process spawned with PID: %s" % pr.pid)
pgid = os.getpgid(pr.pid)
subprocess.check_output("sudo kill {}".format(pgid))
它将终止启动python解释器的进程
it would kill the process that started the python interpreter
>>> Terminated
所以我将preexec_fn
设置为os.setpgrp
import subprocess, os
pr = subprocess.Popen(["sudo", "sleep", "100"], preexec_fn=os.setpgrp)
print("Process spawned with PID: %s" % pr.pid)
pgid = os.getpgid(pr.pid)
subprocess.check_output("sudo kill {}".format(pgid))
在另一个外壳中(如果我检查的话)
in another shell, if I check
pgrep sleep
什么都没有出现,所以实际上被杀死了.
nothing shows up, so it is actually killed.
这篇关于在python中杀死sudo启动的子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!