本人初学python语言,最近写了一个为Linux系统添加用户的脚本,分单个添加,和批量添加。请同行多指教。
代码中用到的模块:
getpass,datetime,os等。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #! /usr/bin/env python 2 # coding=utf-8 3 4 #useradd script 5 #-----------------------------------begin---------------------- 6 7 import os 8 import datetime 9 import time 10 import getpass 11 def open_pass(): 12 ps_wenjian = open('/etc/passwd', 'r',encoding='utf-8') 13 wenjian = ps_wenjian.readlines() 14 ps_wenjian.close 15 return wenjian 16 date1 = datetime.datetime.strftime((datetime.datetime.now() + datetime.timedelta(days=365)), '%Y-%m-%d') 17 user_pass = {} 18 choose = input('Please choose batch create username or single create username (2:batch/1:single): ') 19 choose = int(choose) 20 if choose == 1: 21 while True: 22 open_pass() 23 username = input('please input username: ') 24 password = getpass.getpass('Please enter password: ') 25 for nn in open_pass(): 26 nnn = nn.split(':', 1)[0] 27 if username != nnn: 28 print('create username') 29 os.system('useradd %(name1)s -s /bin/bash' % {'name1':username}) #创建用户 30 os.system('echo %(pass)s |passwd --stdin %(name1)s' % {'name1': username, 'pass':password}) 31 date1 = datetime.datetime.strftime((datetime.datetime.now() + datetime.timedelta(days=365)), '%Y-%m-%d') 32 os.system('chage -E %(dat)s -W 10 -m 30 -M 365 %(name1)s' % {'name1': username, 'dat': date1}) 33 user_pass[username] = password # 将创建的用户和其对应的密码添加到字典中 34 print('Created user! and password add successfully.') 35 break 36 else: 37 print('username is exits,Please again enter username.') 38 break 39 mm = input('Please yes or no (yes/no): ') 40 mm = mm.lower() 41 f = True 42 while f: 43 if mm == 'yes': 44 print('Please continue create username.') 45 f = False 46 else: 47 break 48 if mm == 'no': 49 break 50 51 elif choose == 2: 52 username_list = [] 53 username_numb = input('Please enter create how many users : ') 54 f = True 55 while f: 56 username = input('please input username: ') 57 password = input("Please input password: ") 58 open_pass() 59 for nn1 in open_pass(): 60 nnn1 = nn1.split(':', 1)[0] 61 if username == nnn1: 62 print('username is exists,Please again enter !') 63 break 64 else: 65 f = False 66 for uu in range(1,int(username_numb)+1): 67 print('create username') 68 os.system('useradd %s%s -s /bin/bash' % (username, uu)) #创建用户 69 username_list.append('%s%s'%(username,uu)) 70 for us in username_list: 71 os.system('echo %(pass)s |passwd --stdin %(name1)s' % {'name1': us, 'pass':password}) 72 os.system('chage -E %(dat)s -W 10 -m 30 -M 365 %(name1)s' % {'name1': us, 'dat': date1}) 73 user_pass[us] = password # 将创建的用户和其对应的密码添加到字典中 74 print('Created user! and password add successfully.') 75 else: 76 print('only input 1 or 2') 77 78 print(user_pass) 79 print('Created user! and password add successfully.')