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?
2 Answers
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.
-
drop privilege may work but what about the very first py file?the pyc is still created under the root permission right? – user2003548 Jan 24 '14 at 15:25
-
Did this fix your problem in the end? Don't forget to upvote if it worked for you :) – SleepyCal Jan 31 '14 at 13:58
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.

- 2,739
- 2
- 30
- 29