Many times when registering some of the more important accounts, or using some of the more important interface, need to use to random string, for convenience, we design this script should pay attention to the following points:
- Our password characters are obtained randomly from the 0-9/a-z/a-z. To avoid display confusion, we remove the number 0 in the character and the letter o as well as the number 1 and the letter L.
- A 16-character random password is generated by default when the command is not with a parameter
- The command can take a parameter that indicates the length of the random password that needs to be generated
- To print the password to the terminal, and also need to send a random password to the Clipboard , easy to paste the use
- Place the command under the system path to make it easy to use the command directly.
The code is as follows:
#-*-Coding:utf-8-*-import stringimport sysimport randomimport subprocessalnums = [x for x in String.letters + string.di Gits if x not in (' 0 ', ' o ', ' 1 ', ' L ')] # produces a sample other than the special character Def Genpass (n=16): "" "generates a random password, the default length is 16 characters" "" passwd = List ( ) for I in Range (n): passwd + = Random.choice (alnums) return '. Join (passwd) def write_to_clipboard (output): "" Copies the output content to the Clipboard "" Process = subprocess. Popen (' pbcopy ', env={' LANG ': ' en_US. UTF-8 '}, stdin=subprocess. PIPE) process.communicate (Output.encode (' Utf-8 ')) def main (): If Len (sys.argv) = = 1:PASSWD = Genpass () Print passwd Write_to_clipboard (passwd) elif len (sys.argv) = = 2:try:n = Int (sys.argv[1]) Except Valueerror:print ' Input length of the password ' else:passwd = Genpass (n) Print passwd Write_to_clipboard (passwd) Else:print ' only need a argument:length of the Passwor d ' if __name__ = = ' __main__ ': MaiN ()
Copy the script to the /usr/local/bin following name genpass , give execute permission sudo chmod 700 genpass , and then you can use the Genpass command in TERMIANL.
A python script that generates random passwords for Mac OS