Issue
I'm trying to create a basic python script to change a users password to a stored variable using sub-process, however I can't find anywhere that explains how to have it communicate to the prompts, it only sends commands. Here's a basic outline of what I'm trying to accomplish
import subprocess
import os
pass = root
user = FakeUser
subprocess.call(['sudo passwd', user], shell=True)
Then it asks for a new unix password:
subprocess.call([pass], shell=True)
Then it asked for it again:
subprocess.call([pass], shell=True)
Hopefully that makes sense. I just need the code to communicate with the terminal, not just send the commands.
Solution
You can use the pexpect module for this. passwd
will print out the word password
on every interactive line (it may be capitalized, depending on your system), so the approach I will use here simply has pexpect
wait for the interactive prompt to be printed before sending the next line. passwd
typically asks for the old password once, and the new password twice.
Something like this should work:
import pexpect
def change_password(username, sudo_password, new_password):
process = pexpect.spawn("sudo passwd " + username)
process.expect("password")
process.sendline(sudo_password)
process.expect("password")
process.sendline(new_password)
process.expect("password")
process.sendline(new_password)
process.close()
username = "FakeUser"
sudo_password = "sudopass"
new_password = "new"
change_password(username, sudo_password, new_password)
Update: since you are using sudo
, you will actually be asked for your sudo password first, and then you will be allowed to set the password for an arbitrary user without having to know their original password. I have re-labeled the variables to reflect this. If you want to do this from a user account without sudo privileges, you can still do this, but you will need to switch users first (and likely remove the use of sudo
, which would fail for an unprivileged user).
Answered By - rnorris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.