0

I'm using a python script to control tcpdump. I can start a process of tcpdump just fine from my script. However, when I want to kill the tcpdump process via python:

import subprocess
pid = 9669  # pid of the tcpdump process
subprocess.call(["sudo", "kill", "-9", f"{pid}"])

I receive this error message:

kill: (9669): Permission denied

However, when I open a shell and enter sudo kill -9 9669 it kills the process just fine. The system is configured so that neither sudo tcpdump nor sudo kill will prompt for a password. To my understanding the subprocess.call command and the terminal command should be identical, yet one works and the other doesn't. What am I doing wrong?

  • 1
    Did you run your script with sudo as well? – rdas Oct 03 '22 at 15:03
  • https://stackoverflow.com/questions/5721529/running-python-script-as-root-with-sudo-what-is-the-username-of-the-effectiv – pippo1980 Oct 03 '22 at 15:38
  • The function is called inside of a pytest, which is run executed by pycharm. Pretty sure neither of these is run as `sudo`. What's strange to me is that in another function I call `sudo tcpdump` from inside python, and that executes just fine (it starts an instance of `tcpdump`. However, I seem to be unable to stop this instance of `tcpdump` from inside the same script... – Christian Disch Oct 04 '22 at 05:39
  • There's something else weird about this. The error you get when you try to kill a process from another userid is "Operation not permitted", not "Permission denied". – Barmar Oct 06 '22 at 14:29
  • The documentation of `kill(2)` doesn't even mention `EACCESS` as a possible error code. – Barmar Oct 06 '22 at 14:36
  • Found this: https://stackoverflow.com/questions/56459443/sudo-kill-results-in-permission-denied It has to do with running within a container of some kind. – Barmar Oct 06 '22 at 14:38
  • I found this in the system log: `type=1400 audit(1665402026.962:10594): apparmor="DENIED" operation="signal" profile="/usr/sbin/tcpdump" pid=146275 comm="kill" requested_mask="receive" denied_mask="receive" signal=kill peer="snap.pycharm-professional.pycharm-professional"` How can I exclude pycharm from being restricted by AppArmor? – Christian Disch Oct 10 '22 at 12:11

1 Answers1

1

PyCharm had been installed via snap. This has put PyCharm behind AppArmor. I removed PyCharm via snap, downloaded the PyCharm tar file and did the installation myself. Now my script for stopping tcpdump works as intended from within PyCharm.

Honestly I find it a bit baffling to put a developer tool into a sandbox where some things just won't work due to the restrictive nature of the sandbox.

  • This is a problem of IDE's in general: how they execute your code is not obvious. If you run into something weird in an IDE, first run your code as a script from the command line. If that works, the problem is in the IDE. – Roland Smith Oct 17 '22 at 13:28