forked from robertdebock/my_rpm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuser.py
166 lines (141 loc) · 6.07 KB
/
user.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import subprocess
import time
import re
import os
import random
class UserManage(object):
def __init__(self, *args):
super(UserManage, self).__init__(*args)
def createUser(self, username: str, password: str):
userlist=self.listUser()
user=[]
for user_idx in userlist:
user.append(userlist[user_idx])
if user.__contains__(username)!=True:
subprocess.Popen(["useradd", username, "-s", "/bin/bash", "-d",
"/home/"+username], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
subprocess.getstatusoutput("mkdir -p /data/job/project/"+username)
time.sleep(1)
self.changepassword(username, password)
self.writeSudoersFile(username)
# if self.checkUserExist(username):
# print("Something wrong")
else:print("user exist")
def changepassword(self, username: str, password: str):
result = subprocess.Popen(
["/bin/bash"], stdin=subprocess.PIPE)
result.stdin.write(bytes("passwd "+username+"\n", "utf-8"))
result.stdin.write(bytes(password+"\n", "utf-8"))
result.stdin.write(bytes(password+"\n", "utf-8"))
#不加下面一行输出会乱
result.communicate()[0]
print(username+" password is "+password)
def writeSudoersFile(self, username: str):
subprocess.Popen(["chmod","u+w","/etc/sudoers"],stdin=subprocess.PIPE)
with open("/etc/sudoers", mode="r+") as file:
if file.read().find(username)!=True:
file.write(username+" ALL=(ALL) ALL\n")
file.flush()
file.close()
#先读取文件,把包含username的这一行删掉,在新建一个文件把字符串写进去
def deleteSudoersLine(self, username: str):
subprocess.Popen(["chmod","u+w","/etc/sudoers"],stdin=subprocess.PIPE)
sudoersString = ""
with open("/etc/sudoers", mode="r") as file:
for line in file.readlines():
if username not in line:
sudoersString += line
with open("/etc/sudoers",mode="w") as file:
file.write(sudoersString)
def deleteUser(self, username: str):
subprocess.Popen(["userdel", "-r", username],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
self.deleteSudoersLine(username)
# subprocess.Popen(["rm","-rf","/home/"+username],stdin=subprocess.PIPE)
#if self.checkUserExist(username) == True:
# print("Something wrong")
print(" user "+username+" delete success!")
def checkUserExist(self, username: str) -> bool:
result = subprocess.Popen(
["id", "-u", username], stdin=subprocess.PIPE,stdout=subprocess.PIPE)
if result.communicate()[0].isdigit():
return True
return False
def listUser(self) -> dict:
file = open("/etc/passwd", mode="r")
userMap = dict()
userlist = []
i = 0
for line in file.readlines():
userlist = re.search("(.*):x(.*?):/home/(\w)", line, re.M)
if userlist!=None:
userMap[str(i)] = userlist.group(1)
i = i+1
return userMap
class Interact(object):
selectString = '''
Select what you will do to the user:
0.add user
1.delete user
2.reset user password
'''
inputUsernameString = '''
Please input username
'''
inputPasswordString = '''
Please input password
'''
def __init__(self, *args):
super(Interact, self).__init__(*args)
self.select = ""
def getSelection(self) -> str:
self.select = input(self.selectString+"-> ")
while self.select != "0" and self.select != "1" and self.select != "2":
self.select = input("Error please try again \n-> ")
return self.select
def getInputUsername(self) -> str:
self.username = input(self.inputUsernameString+"-> ")
return self.username
def getInputPassword(self) -> str:
self.password = input(self.inputPasswordString+"-> ")
return self.password
def getResetPasswordSelection(self, userlist: dict) -> str:
self.userSelectString = ""
for key in userlist.keys():
sigleLine = " "+key.strip()+" " + \
userlist[key].strip()+"\n"
self.userSelectString += sigleLine
self.userSelect = input(self.userSelectString+"-> ")
while userlist.get(self.userSelect) == None:
self.userSelect = input("Error please try again\n -> ")
return userlist[self.userSelect]
def getDeleteUserSelection(self, userlist: dict) -> str:
self.userSelectString = ""
for key in userlist.keys():
sigleLine = " "+key.strip()+" " + \
userlist[key].strip()+"\n"
self.userSelectString += sigleLine
self.userSelect = input(self.userSelectString+"-> ")
while userlist.get(self.userSelect) == None:
self.userSelect = input("Error please try again\n -> ")
return userlist[self.userSelect]
def randomPassword(len: int) -> str:
password = ""
passwordCharact = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "A","B","C","D","E", "d", "f",
"E","F","G","H","I","J", "K", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "@","$", "#", "&","*", "!"]
random.shuffle(passwordCharact)
for _ in range(len):
password += str(random.choice(passwordCharact))
return password
if __name__ == '__main__':
usermamege = UserManage()
interact = Interact()
selection = interact.getSelection()
if selection == "0":
usermamege.createUser(interact.getInputUsername(),
randomPassword(16).strip())
elif selection == "1":
usermamege.deleteUser(interact.getDeleteUserSelection(usermamege.listUser()))
else:
usermamege.changepassword(
interact.getResetPasswordSelection(usermamege.listUser()), randomPassword(16).strip())