Demand:
Batch new 10 test users, and let their password randomly, the user name and password to write a file, and have the creation time and creator
#!/usr/bin/python#-*-coding:utf-8-*-import osimport randomimport timeimport iodef deluser (nums): "Delete user test user" For I in Range (nums): username = ' Stu ' + str (i) Linux_cmd = ' Userdel-r {username} '. Format (username=username ) Cmd_stat = Os.system (linux_cmd) if Cmd_stat = = 0:print (username + "Userdel:ok") Else: Print (username + "Userdel:fail") def create_user (Nums, Record_adduser): ' Add user test user ' if Isinstance (nu MS, str): nums = Int (nums) symbol = ' 1234567890 ' if not os.path.exists (Os.path.dirname (record_adduser)): # No this directory created Os.mkdir (Os.path.dirname (Record_adduser) #) # This file opens directly without creating F = io.open (Record_adduser, ' A + ', en coding= ' Utf-8 ') for I in Range (nums): passwd = ". Join (Random.sample (symbol, 6)) Username = ' Stu ' + str (i ) Linux_cmd = ' Useradd {username} && echo ' {passwd} ' | passwd {username}--stdin{linesep} '. Format (Username=username, PASSWD=PASSWD, LINESEP=OS.LINESEP) Current_User = Os.popen (' WhoAmI '). Read (). Strip () Cmd_stat = Os.system (linux_cmd) tmp = str (time.strftime ('%Y -%m-%d%h:%m ', Time.localtime ()) + ' + current_user + ' + linux_cmd + ' {stat} ') if Cmd_stat = = 0:print (username + "Useradd:ok") tmp = Tmp.format (stat= ' OK '). Decode (' Utf-8 ') # created as Write a sentence f.write (TMP) Else:print (username + "Useradd:fail") tmp = Tmp.format (stat= ' FAIL '). Decode (' Utf-8 ') f.write (TMP) # F.flush () f.close () if __name__ = = ' __main__ ': record_adduser = '/root/adduser{sep}useradd.log '. Format (SEP=OS.PATH.SEP) Create_user (Ten, Record_adduser) # Deluser (Ten) # python 2 , str is the bytes type and the file is opened via IO module
Linux adds 10 users in bulk and writes their random password and username to a file