-
Notifications
You must be signed in to change notification settings - Fork 34
/
random
executable file
·74 lines (63 loc) · 2.41 KB
/
random
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
#!/usr/bin/env python
import os, sys, string
def get_terminal_size():
def ioctl_GWINSZ(fd):
try:
import fcntl, termios, struct
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
except: return
return cr
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except: pass
if not cr: cr = 0, 0
return int(cr[1]), int(cr[0])
def main(args=None):
import argparse
parser = argparse.ArgumentParser(description='Generate a pseudorandom strings.')
parser.add_argument('-n', '--length',
type=int, default=39, metavar='n',
help='Length of a produced string. Default: %(default)s')
parser.add_argument('-r', '--rows',
type=int, default=10, metavar='n',
help='Rows of passwords to produce. Default: %(default)s')
parser.add_argument('-s', '--simple',
action='store_true', help='Use only letters/numbers.')
parser.add_argument('-d', '--digits',
action='store_true', help='Use only numbers (digits).')
parser.add_argument('-x', '--hex-digits',
action='store_true', help='Use numbers + a-f lowecase hex digits.')
parser.add_argument('-1', '--one',
action='store_true', help='Output just one generated password.')
opts = parser.parse_args(sys.argv[1:] if args is None else args)
if sum(map(bool, [opts.digits, opts.simple])) > 1:
parser.error('Multiple output modes specified at the same time')
if opts.digits: chr_range = string.digits.encode()
elif opts.hex_digits: chr_range = (string.digits + 'abcdef').encode()
elif opts.simple: chr_range = (string.ascii_letters + string.digits).encode()
else:
chr_range = (string.ascii_letters + string.digits).encode()
chr_range += ( string.punctuation.replace("'", '').replace('"', '')
.replace('`', '').replace('\\', '').replace('!', '').replace('$', '') ).encode()
def src():
with open('/dev/urandom', 'rb') as src:
while True: yield src.read(1)
src = (c for c in src() if c in chr_range)
getpass = lambda n: bytearray(ord(next(src)) for m in range(n)).decode()
if opts.one:
return print(getpass(opts.length))
(w, h), pad = get_terminal_size(), 3
for n in range(opts.rows):
row_left = w
while True:
print(getpass(opts.length), end='')
row_left -= opts.length
if not row_left or row_left < (pad + opts.length): break
print(' '*pad, end='')
row_left -= pad
print()
if __name__ == '__main__': sys.exit(main())