Changing password, python, linux
How can i change password of ubuntu root user by pyth开发者_如何转开发on script? Thanks.
There are two main ways to go about this -
One is calling the passwd command line tool from python (such as via stdlib's subprocess module). If your script isn't running as root, you'll need to wrap using the "su" or "sudo" commands in order to elevate to root privledge. Writing the expected data to stdin should be sufficient, but if you find you need to perform different actions based on exactly what the sudo/passwd prompts say, the pexpect module may be helpful.
The second is writing directly to the /etc/shadow file where the password hashes are stored. This will definitely require your script to run as root, in order to have read/write perms on /etc/shadow. Stdlib offers the spwd module for accessing /etc/shadow, but it's read-only, so you'll have to roll your own reader/writer... the csv module might be useful, /etc/shadow is close to being a csv file with a ":" separator, but with some minor differences.
If you choose the second route, you'll need to be able to generate new hashes of replacement password, and insert them into the shadow file. The fastest way on linux is to use the stdlib crypt module, but you'll have to take care of salt generation, and setting the appropriate password hash prefix ("$5$", "$6$" etc). Alternately, the host_context object in the Passlib library can take care of most of that for you (disclaimer: I'm the author of that library).
In general, I'd recommend the first route if possible - modifying /etc/shadow directly is fraught with danger - if you mess up the /etc/shadow file, you won't be able to log in. If you go this route, back up the file a lot.
You can modify /etc/passwd
(/etc/shadow
) with Python script which will need root permissions sudo python modify.py /etc/passwd
(where modify.py
is your script that will change password)
You can use the commands module to pipe output to the terminal.
x = commands.getstatusoutput("passwd root")
However, you'll have to get creative trying to enter the values for "Old Password:" and "New Password:." The variable x wont be assigned until the command is finished, and the command won't finish until the old and new passwords are entered. If you just use the command module a second time, then it will simply spawn a new subprocess. So, like others have said, just write to /etc/shadow using the open function.
精彩评论