为什么当我尝试结束Python子进程时,terminate()会收到“权限被拒绝”的信息?

时间:2020-07-23 20:40:30

标签: python subprocess

我正在尝试使用下面的代码将TCPDump作为Python的子进程运行,但是p.terminate()无法终止该进程,而我能够杀死它的唯一方法是使用sudo kill(pid) cli。

这是我要运行的代码...

import subprocess
import time
from datetime import datetime


def TCPDump():
    path_to_output_file = '/home/user/output.txt'
    myoutput = open(path_to_output_file, 'w+')
    func_name = "AutoTCPDump"

    print(func_name + "start")
    print(func_name + "about to create capture")
    p = subprocess.Popen(["tcpdump",
                          "-U",
                          "-i", "enp0s8",
                          "-w", "/home/user/Test.pcap"],
                         stdout=myoutput, stderr=myoutput, universal_newlines=True)

    time.sleep(10)
    print("end")
    p.terminate()

TCPDump()

这是我收到的错误...

Traceback (most recent call last):
  File "TCPDump2.py", line 24, in <module>
    TCPDump()
  File "TCPDump2.py", line 20, in TCPDump
    p.terminate()
  File "/usr/lib/python3.6/subprocess.py", line 1605, in terminate
    self.send_signal(signal.SIGTERM)
  File "/usr/lib/python3.6/subprocess.py", line 1600, in send_signal
    os.kill(self.pid, sig)
PermissionError: [Errno 13] Permission denied

代码在Ubuntu 18.0.04 Desktop上运行,并且我修改了系统权限,以允许TCPDump以标准用户身份运行,并且可以从cli进行交互。

任何帮助/建议都非常感谢。 谢谢

对此进行更新,在syslog中查看,看来apparmour在这里存在一些问题...

Jul 25 10:05:11 matt-VirtualBox kernel: [ 2412.365557] audit: type=1400 audit(1595667911.307:279): apparmor="DENIED" operation="file_inherit" profile="/usr/sbin/tcpdump" name="/dev/pts/2" pid=14069 comm="tcpdump" requested_mask="wr" denied_mask="wr" fsuid=1000 ouid=1000

Jul 25 10:05:11 matt-VirtualBox kernel: [ 2412.365560] audit: type=1400 audit(1595667911.307:280): apparmor="DENIED" operation="file_inherit" profile="/usr/sbin/tcpdump" name="/dev/pts/2" pid=14069 comm="tcpdump" requested_mask="wr" denied_mask="wr" fsuid=1000 ouid=1000

Jul 25 10:05:11 matt-VirtualBox kernel: [ 2412.365561] audit: type=1400 audit(1595667911.307:281): apparmor="DENIED" operation="file_inherit" profile="/usr/sbin/tcpdump" name="/dev/pts/2" pid=14069 comm="tcpdump" requested_mask="wr" denied_mask="wr" fsuid=1000 ouid=1000

Jul 25 10:05:11 matt-VirtualBox kernel: [ 2412.365563] audit: type=1400 audit(1595667911.307:282): apparmor="DENIED" operation="file_inherit" profile="/usr/sbin/tcpdump" name="/dev/pts/2" pid=14069 comm="tcpdump" requested_mask="wr" denied_mask="wr" fsuid=1000 ouid=1000

Jul 25 10:05:21 matt-VirtualBox kernel: [ 2422.379112] audit: type=1400 audit(1595667921.318:283): apparmor="DENIED" operation="signal" profile="/usr/sbin/tcpdump" pid=14068 comm="python3" requested_mask="receive" denied_mask="receive" signal=term peer="snap.pycharm-community.pycharm-community"

我对阅读这些日志不是很熟悉,对可能发生的情况有何建议?

1 个答案:

答案 0 :(得分:0)

我发现了问题-这是Apparmour阻止了对TCPdump的访问。 在Apparmour中禁用TCPDump配置文件解决了该问题