0

I need to listen linux's port to run my service. So, I always run the python program to start with sudo previlage, that made the files created by program like pycahee and .pyc files also get super user's authority,the files and directories can only be removed in sudo mode. That's very inconvenience. So, is there a way to specify python to create normal folder and files?

Santosh Ghimire
  • 3,087
  • 8
  • 35
  • 63
user2003548
  • 4,287
  • 5
  • 24
  • 32

2 Answers2

0

Running a script as root just so you can listen on privileged ports is not good practise (unless the script really does require root).

If your script doesn't require root, then I would recommend using setuid/setgid to drop privileges after you have set up the privileged port socket;

This has already been answered in detail here;

Dropping Root Permissions In Python

Edit: OP mentioned that the pyc file created still has root permissions. You could use the suid bit (chmod u+s script.py) then setuid(0) to gain root permissions during runtime, ensuring the file ownership is not root. Setting the suid bit for only the file owner also means other users cannot abuse the suid bit.

Community
  • 1
  • 1
SleepyCal
  • 5,739
  • 5
  • 33
  • 47
0

A potential strategy is to run compileall as your normal user first so that the pyc files already exist and root doesn't have to create them.

python -m compileall

Documentation is here.

Eric Smith
  • 2,739
  • 2
  • 30
  • 29