I would like to restrict ability to run my Python 3 script to certain host and users on Linux. Is there any Python 3.x build in function or library which would allow me to do this relatively easy please?
Asked
Active
Viewed 1,715 times
1
-
3You want to restrict your scripts execution permissions from within the script itself? For that it would have to be executed first. – UnholySheep Jan 03 '17 at 10:02
-
Are you need to restrict only a given script or running Python scripts at all? – Pax0r Jan 03 '17 at 10:04
-
Correct, once script checks user and host name it will either continue to run or stop and exit. – Yat Jan 03 '17 at 10:05
-
You have the `os` module, e.g.: [`os.getlogin`](https://docs.python.org/3/library/os.html?highlight=os#os.getlogin) and [`os.getgrouplist`](https://docs.python.org/3/library/os.html?highlight=os#os.getgrouplist) - also see [this question](http://stackoverflow.com/questions/842059/is-there-a-portable-way-to-get-the-current-username-in-python) – UnholySheep Jan 03 '17 at 10:11
-
@UnholySheep - many thanks that's also useful. – Yat Jan 03 '17 at 23:43
2 Answers
3
Not exactly a Python answer, but a Linux one - you may add all users who can run a script to some group:
groupadd allowed-users
usermod -a -G allowed-users some-user
Then change group of the script and restrict read access to it only for group (if user can't read a script it can't run it).
chown allowed-users script.py
chmod 640 script.py

Pax0r
- 2,324
- 2
- 31
- 49
1
I'm sure there is a better way of doing that but below is my first attempt.
#!/usr/bin/python3
import getpass
import socket
hostname = socket.gethostname()
username = getpass.getuser()
allowedusers = 'user1'
allowedhosts = 'host1'
if hostname in allowedhosts:
print('hostname allowed')
if username in allowedusers:
print('user allowed')
else:
print('username not allowed')
exit()
else:
print('hostname not allowed')
exit()
print('script will continue to run as hostname and user are allowed')

Yat
- 39
- 6
-
1Be aware of the fact that acording to docs https://docs.python.org/2.7/library/getpass.html getpass just checks some env variables, so if user runs a script as `LOGNAME='not-really-me' python script.py` then `getuser()` will return `not-really-me`. I strongly recommend doing such checks on the OS level. – Pax0r Jan 03 '17 at 13:19
-
1@pax0r I agree, however this is only sort of exercise rather than production with expectations to be super secure. Thanks for your feedback. – Yat Jan 03 '17 at 13:24
-
even if so, still someone else may read this, so it is worth noticing ;) – Pax0r Jan 03 '17 at 13:34