python案例2

需求

在新安装的linux系统服务器上要安装多个不同用户权限的应用,
如何批量创建用户、初始化工作目录

分析

1.使用配置文件来记录applications、os user、workspace权限等信息
如配置文件config-app1内容如下:
os_user=user1 操作系统用户名
workspace=/home/apps/app1
service_group=common

2.使用python调用os命令创建文件夹、用户、分配权限

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import os;

##判断用户是否存在
def userExis(username) :
flag = 0;
with open("/etc/passwd", 'r') as passwdFile:
for line in passwdFile.readlines():
if(line.split(":")[0]==username): ##判断该用户是否存在
flag = 1;
break;
return flag;

## 获取工作目录
workdir = os.path.abspath(os.getcwd() + os.path.sep + "..")

## 遍历conf下的config文件
for f in os.listdir(workdir + os.path.sep + "conf"):
if(f.startswith("config-")):
# file
with open(workdir + os.path.sep + "conf"+ os.path.sep+f, 'r') as conffile:
allLines = conffile.readlines();
for line in allLines:
cls = line.split("=")
username = "";
if("os_user"==cls[0]):
username = cls[1]

if(userExis(username)==0): ## 不存在该用户拒创建用户
os.system("useradd "+username);

os.mkdir("/home/apps/"+username)
os.chown("/home/apps/"+username, username)