How can I set a users password in linux from a python script?

回眸只為那壹抹淺笑 提交于 2019-11-28 07:05:19

The documentation for communicate says that you'll need to add stdin=PIPE if you're sending data to standard input via the communicate parameter:

http://docs.python.org/release/2.6/library/subprocess.html#subprocess.Popen.communicate

I appreciate this is just skeleton code, but here are another couple of other small comments, in case they are of use:

  • If you're not interested in the output of the useradd command other than whether it failed or not, you might be better off using subprocess.check_call which will raise an exception if the command returns non-zero.
  • In the second case, you should check whether process.returncode is 0 after your call to communicate('test:password')
Senthil Murugan

Try below code which will do as you required automation

from subprocess import Popen, PIPE, check_call  
check_call(['useradd', 'test'])   
proc=Popen(['passwd', 'test'],stdin=PIPE,stdout=PIPE,stderr=PIPE)  
proc.stdin.write('password\n')  
proc.stdin.write('password')  
proc.stdin.flush()  
stdout,stderr = proc.communicate()  
print stdout  
print stderr

print statements are optional.

You forgot this:

stdin=subprocess.PIPE

To send data to the process, you need a stdin.

So the full statement is:

process = subprocess.Popen(['sudo', 'chpasswd'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

and then call communicate('password').

zarat

On Ubuntu, use usermod

class SomeClass
    def userPasswd(self, login, password):
        encPass = crypt.crypt(password)
        command = "usermod -p '{0:s}' {1:s}".format(encPass, login)
        result = os.system(command)
        if result != 0:
            logging.error(command)
        return result

I guess the issue is that you forgot the -S option for sudo.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!