How to change a Linux user password from python

Posted by Vaulor on Stack Overflow See other posts from Stack Overflow or by Vaulor
Published on 2012-11-01T14:24:34Z Indexed on 2012/11/02 11:01 UTC
Read the original article Hit count: 282

Filed under:
|
|
|

I'm having problems with changing a Linux user's password from python. I've tried so many things, but I couldn't manage to solve the issue, here is the sample of things I've already tried:

sudo_password is the password for sudo, sudo_command is the command I want the system to run, user is get from a List and is the user who I want to change the password for, and newpass is the pass I want to assign to 'user'

    user = list.get(ANCHOR)
    sudo_command = 'passwd'
    f = open("passwordusu.tmp", "w")
    f.write("%s\n%s" % (newpass, newpass))
    f.close()
    A=os.system('echo -e %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user))
    print A
    windowpass.destroy()

'A' is the return value for the execution of os.system, in this case 256. I tried also

    A=os.system('echo  %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user))

but it returns the same error code. I tried several other ways with 'passwd' command, but whithout succes. With 'chpasswd' command I 've tried this:

    user = list.get(ANCHOR)
    sudo_command = 'chpasswd'
    f = open("passwordusu.tmp", "w")
    f.write("%s:%s" % (user, newpass))
    f.close()
    A=os.system('echo %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user))
    print A
    windowpass.destroy()

also with:

    A=os.system('echo %s|sudo -S %s:%s|%s' % (sudo_password, user, newpass, sudo_command))
    @;which returns 32512
    A=os.system("echo %s | sudo -S %s < \"%s\"" % (sudo_password, sudo_command,  "passwordusu.tmp"))
    @;which returns 256

I tried 'mkpasswd' and 'usermod' too like this:

    user = list.get(ANCHOR)
    sudo_command = 'mkpasswd -m sha-512'
    os.system("echo %s | sudo -S %s %s > passwd.tmp" % (sudo_password,sudo_command, newpass))
    sudo_command="usermod -p"
    f = open('passwd.tmp', 'r')
    for line in f.readlines():
        newpassencryp=line
    f.close()
    A=os.system("echo %s | sudo -S %s %s %s" % (sudo_password, sudo_command, newpassencryp, user))
    @;which returns 32512

but, if you go to https://www.mkpasswd.net , hash the 'newpass' and substitute for 'newpassencryp', it returns 0 which theoretically means it has gone right, but so far it doesn't changes the password.

I've searched on internet and stackoverflow for this issue or similar and tried what solutions exposed, but again,without success.

I would really apreciate any help, and of course, if you need more info i'll be glad to supply it!

Thanks in advance.

© Stack Overflow or respective owner

Related posts about python

Related posts about linux