Skip to content

Instantly share code, notes, and snippets.

@wention
Created December 18, 2019 08:09
Show Gist options
  • Select an option

  • Save wention/d07c3d20c8b2663094e64d259fd4f5e4 to your computer and use it in GitHub Desktop.

Select an option

Save wention/d07c3d20c8b2663094e64d259fd4f5e4 to your computer and use it in GitHub Desktop.
Reset linux system password
import os
import sys
import base64
import crypt
def hash_passwd(passwd):
# SHA-512
return crypt.crypt(passwd, "$6$" + base64.b64encode(os.urandom(16)))
def update_userpasswd(username, password):
with open('/etc/shadow', 'rb') as fd:
shadow_rows = fd.readlines()
found = False
for index, row in enumerate(shadow_rows):
if row.startswith(username):
found = True
cols = row.split(':')
cols[1] = hash_passwd(password)
shadow_rows[index] = ':'.join(cols)
if found:
with open('/etc/shadow', 'wb') as fd:
fd.write(''.join(shadow_rows))
return True
return False
if __name__ == '__main__':
if len(sys.argv) != 3:
print "%s [username] [password]" % sys.argv[0]
os._exit(1)
if not update_userpasswd(sys.argv[1], sys.argv[2]):
os._exit(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment