Yat
Yat

Reputation: 39

How to restrict permission to run script?

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?

Upvotes: 1

Views: 2120

Answers (2)

Yat
Yat

Reputation: 39

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')

Upvotes: 1

Pax0r
Pax0r

Reputation: 2473

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

Upvotes: 3

Related Questions