如何限制运行脚本的权限?

时间:2017-01-03 09:59:48

标签: python python-3.x

我想限制将Linux 3脚本运行到Linux上的某些主机和用户的能力。是否有任何Python 3.x版本的功能或库可以让我这样做相对容易吗?

2 个答案:

答案 0 :(得分:3)

不完全是Python答案,而是Linux答案 - 您可以将可以运行脚本的所有用户添加到某个组:

groupadd allowed-users 
usermod -a -G allowed-users some-user

然后更改脚本组并限制对组的读访问权限(如果用户无法读取脚本则无法运行它)。

chown allowed-users script.py
chmod 640 script.py

答案 1 :(得分:1)

我确信有更好的方法,但下面是我的第一次尝试。

#!/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')