sudo’ng Pycharm

I recently had occasion to write a simple python (3) script under debian buster with JetBrains’ Pycharm. The script rewrites protected system files so it needs sudo privileges…which turned out to be a pain to provide during development.

You can find the basic instructions here (thanx, Eric!). Conceptually, you’re doing three things:

  • configure sudo, via a sudoers.d file (/etc/sudoers.d/python) to allow your user account to run python in root mode without having to supply your credentials;
  • create a shell script that simply runs python, passing in whatever command line arguments it’s given; and,
  • edit your python project’s virtual environment so that it uses that shell script as its python interpreter.

The challenge is that either Pycharm or python or both are very persnickety when it comes to file names.

I’ve read that you should make sure the shell script file name “starts with” python (I originally called mine python3-sudo.sh, but during several hours of frustrating work I changed it to python-sudo.sh…just in case “starts with” literally meant “starts with”).

The more important gotcha was that the executable reference in /etc/sudoers.d/python must match the executable reference in the python-sudo.sh script. They can’t refer to different files, even if those files are binary identical (which is the case with the python, python3 and python3.7 executables are in the venv/bin directory). The sudo permission is associated with the file name, not the nature of the executable.

In retrospect this is pretty obvious. My confusion probably stems from my .NET background (where I do most of my programming). The .NET environment associates tons of metadata with each executable, so permissions can, and often are, associated with the contents of the executable, not its name.

So the full path file names in these two files need to match:

/etc/sudoers.d/python (edit only via sudo visudo!)

mark sherlock = (root) NOPASSWD:  /home/mark/PycharmProjects/maestro/venv/bin/python

/home/PycharmProjects/maestro/venv/bin/python-sudo.sh (you can probably put this file anywhere, I just chose to include it in the venv directory)

#!/bin/bash
sudo /home/mark/PycharmProjects/maestro/venv/bin/python "$@"

Personally, I think the Pycharm error message is pretty poor. It doesn’t give you a hint as to what’s gone wrong. It’s probably trying to use the default python executable — 2.7 on my system — when it detects a mismatch because the python-sudo.sh fails due to not being permitted by /etc/sudoers.d/python. But that’s life :).

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Archives
Categories