Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to script in Python to change user passwords in Linux? if so, how?

I'm trying to write some scripts in Python and stumbled upon the need of making something to update the password of a given user in a Linux system...

UPDATE: the objective is to achieve the script to update the password automatically from a given data/algorithm. The important thing is to have no human intervention...

is there a way to achieve that? or should I search through other means?

Thanks!

like image 682
Javier Novoa C. Avatar asked Jan 20 '11 15:01

Javier Novoa C.


1 Answers

You can use openssl and usermod:

#!/usr/bin/env python
import subprocess

login = 'username'
password = 'somepassword'

# OpenSSL doesn't support stronger hash functions, mkpasswd is preferred
#p = subprocess.Popen(('openssl', 'passwd', '-1', password), stdout=subprocess.PIPE)
p = subprocess.Popen(('mkpasswd', '-m', 'sha-512', password), stdout=subprocess.PIPE)
shadow_password = p.communicate()[0].strip()

if p.returncode != 0:
    print 'Error creating hash for ' + login

r = subprocess.call(('usermod', '-p', shadow_password, login))

if r != 0:
    print 'Error changing password for ' + login
like image 142
Juliusz Gonera Avatar answered Sep 27 '22 22:09

Juliusz Gonera