简体   繁体   中英

Changing password, python, linux

How can i change password of ubuntu root user by python 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 .

您可以使用需要根权限的Python脚本修改/etc/passwd/etc/shadowsudo python modify.py /etc/passwd (其中modify.py是您的脚本,它将更改密码)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM