Created
June 17, 2017 21:45
-
-
Save pyratebeard/1f343228c98d0ddeebce1b8a502c77f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import string | |
import random | |
import hashlib | |
import fileinput | |
import os | |
# function to generate a random password of 12 characters, using upper/lowercase letters, | |
# digits, and a small group of punctuation characters. | |
# can change size by passing number - i.e. pass_generator(6) | |
def pass_generator(size=12, chars=string.letters + string.digits + '!%&*-+<>'): | |
# using random.SystemRandom().choice() instead of random.choice() uses /dev/urandom. | |
# this is a cryptographically secure PRNG (pseudorandom number generator). | |
return ''.join(random.SystemRandom().choice(chars) for _ in range(size)) | |
def grub_conf(grub_passwd): | |
grub_md5 = hashlib.md5(grub_passwd).hexdigest() | |
pass_line = 'password --md5 %s' % grub_md5 | |
processing_lines = False | |
for line in fileinput.input('/boot/grub/grub.conf', inplace=1): | |
if line.startswith('default=0'): | |
processing_lines = True | |
else: | |
if processing_lines: | |
print pass_line | |
processing_lines = False | |
print line, | |
def passwd_file(root_passwd, grub_passwd): | |
f = open('/root/.password', 'w') | |
content = 'root %s\ngrub %s\n' % \ | |
(root_passwd, grub_passwd) | |
f.write(content) | |
f.close | |
def change_passwd(root_passwd): | |
# bash command for changing root password | |
os.system('echo "%s" | passwd --stdin root' % root_passwd) | |
def main(): | |
# collect the root and grub passwords | |
root_passwd = pass_generator() | |
grub_passwd = pass_generator() | |
# enter the md5 hash of grub password into /boot/grub/grub.conf | |
grub_conf(grub_passwd) | |
# write the passwords to .password file | |
# will overwrite if file exists | |
passwd_file(root_passwd, grub_passwd) | |
# change the root password | |
change_passwd(root_passwd) | |
print ''' | |
The root and grub passwords have been set. | |
root %s | |
grub %s | |
See /root/.password for details. | |
''' % (root_passwd, grub_passwd) | |
finished = '' | |
finished = raw_input('Please make a note of the root password then press "y": ') | |
while True: | |
if finished != 'y': | |
continue | |
else: | |
break | |
if __name__ == '__main__': | |
try: | |
main() | |
except Exception, e: | |
print str(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment