Change unix password with Python

Posted by cikul | Posted in Python | Posted on 11-01-2007-05-2008


Do you ever have problem while execute /usr/bin/passwd from your python code? actually i have problem with changing unix password from my python code.

First i try using pipe to control output from /usr/bin/passwd, hopefully i can send text with write() function.
this is the code :

import os
COMMAND = 'passwd'
PASSWD  = 'mypassword'

# open a pipe to passwd program and
# write the data to the pipe
p = os.popen("%s" % COMMAND, 'w')

But i failed to change the password.

The solution is use Pexpect

this is the description from the site :

Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their output. Pexpect works like Don Libes’ Expect. Pexpect allows your script to spawn a child application and control it as if a human were typing commands.

Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts for duplicating software package installations on different servers. It can be used for automated software testing. Pexpect is in the spirit of Don Libes’ Expect, but Pexpect is pure Python. Unlike other Expect-like modules for Python, Pexpect does not require TCL or Expect nor does it require C extensions to be compiled. It should work on any platform that supports the standard Python pty module. The Pexpect interface was designed to be easy to use.

i try to use pexpect with this simple code :

'''Change password for one user.
A production version would handle exceptions, explain that it can
only be run as 'root', and so on.

import pexpect, sys

if len(sys.argv) != 3:
print "Usage:  "+sys.argv[0]+" user new_password."
(user, new_password) = (sys.argv[1], sys.argv[2])
child = pexpect.spawn("passwd %s" % user)

for repeat in (1, 2):
child.expect("password: ")

And it’s work!

Share and Enjoy

Comments posted (2)

I have change successly use code below


import os

p = os.popen(‘/usr/bin/passwd’, ‘w’)

i have try that code, but in some linux box does not work. Thank’s for share

Write a comment