How to change a Linux user password from python

后端 未结 6 844
心在旅途
心在旅途 2021-01-03 08:23

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

6条回答
  •  执笔经年
    2021-01-03 08:31

    As mentioned before passing passwords on the command line is not very secure unfortunately. Additionally something like "--stdin" for passwd is not available on every passwd implementation. Therefor here is a more secure version using chpasswd:

    def setPassword(userName:str, password:str):
        p = subprocess.Popen([ "/usr/sbin/chpasswd" ], universal_newlines=True, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (stdout, stderr) = p.communicate(userName + ":" + password + "\n")
        assert p.wait() == 0
        if stdout or stderr:
            raise Exception("Error encountered changing the password!")
    

    Explanation:

    With subprocess.Popen we launch an instance of chpasswd. We pipe the user name and password to an instance of chpasswd. chpasswd will then change the password using the settings defined for the current operating system. chpasswd will remain completely silent if no error occurred. Therefor the code above will raise an exception if any kind of error occurred (without having a closer look to the actual error).

提交回复
热议问题