使用pexpect杀死sudo/root进程

ste*_*fin 1 python pexpect python-2.7

鉴于使用sudo打开的pexpect衍生进程,如下所示:

#!/usr/bin/env python
import pexpect

cmd = ['sudo', 'bash', '-c', '"some long-running sudo command"']
cmd = ' '.join(cmd)
child = pexpect.spawn(cmd, timeout=60)

i = child.expect([
  'success',
  'error'])
if i == 0:
  print('ok')
else:
  print('fail')
  # insert code here
Run Code Online (Sandbox Code Playgroud)

如何在失败时取消此过程(或成功,就此而言)?

我尝试过以下(替换# insert code here):

child.kill(0)
child.close(force=True)
Run Code Online (Sandbox Code Playgroud)

两者都给出了以下错误,这是有道理的,因为Python脚本不是根进程,并且它试图杀死一些根进程.

Traceback (most recent call last):
  File "./myscript.py", line 85, in <module>
    requires_qemu()
  File "./myscript.py", line 82, in requires_qemu
    child.close(0)
  File "/usr/lib/python2.7/site-packages/pexpect/__init__.py", line 747, in close
    raise ExceptionPexpect('Could not terminate the child.')
pexpect.ExceptionPexpect: Could not terminate the child.
Run Code Online (Sandbox Code Playgroud)

由于文件权限(从阻止root访问的共享NFS驱动器运行),无法以root身份运行脚本

poo*_*lie 6

使用sudo杀它作为根:

subprocess.call(['sudo', 'kill', str(child.pid)])
Run Code Online (Sandbox Code Playgroud)