标签:
很多时候在注册一些比较重要的帐号,或者使用一些比较重要的接口的时候,需要使用到随机字符串,为了方便,我们设计这个脚本需要注意以下几点:
代码如下:
# -*- coding:utf-8 -*-
import string
import sys
import random
import subprocess
alnums = [x for x in string.letters + string.digits if x not in (‘0‘, ‘o‘, ‘1‘, ‘l‘)] # 产生除了特殊字符之外的样本
def genpass(n=16):
""" 产生随机密码,默认长度为16个字符 """
passwd = list()
for i in range(n):
passwd += random.choice(alnums)
return ‘‘.join(passwd)
def write_to_clipboard(output):
""" 把output内容复制到剪贴板 """
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 password‘
if __name__ == ‘__main__‘:
main()
把脚本复制到/usr/local/bin
下面名为genpass
,赋予执行权限sudo chmod 700 genpass
, 然后就可以在Termianl中使用genpass命令了。
标签:
原文地址:http://blog.csdn.net/tangch0516/article/details/51364163