hi.I want play linux shells command with python.for example i did it:

def add(userName, pasword):
    import os
    os.system("useradd -d /home/%s  -m -p %s %s"%(userName, pasword, userName))

but some where i have problem.
for example when you want change the users password you have to send the command for changing password and then the shell wants you to enter the password and at the next it wants you to retype the password.
how can i answer its questions witch asks after a commands play?

If you are running the Python script in a terminal, this should be no problem.

I made following script:

import os
username = 'testuser'
password = 'testps2010'
os.system("useradd -d /home/%s -m -p %s %s" % (username, password, username))
os.system("passwd %s" % username)

Running it, gave the next results. The password was changed without a problem.

[root@pavilion Temp]# python user.py
Changing password for user testuser.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.
[root@pavilion Temp]#

I want to do every thing in pythons scripts.
Some thing like below pseudo code:

execute in shell("change password")
if shells result was "New password: "
    send to shell("my new password")
if shells result was "Retype new password: "
    send to shell("my new password")

every things managed in pythons scripts an there are no need to write any thing.

sorry.I saw links but i can not solve my problem yet.
I say my problem again.it may be you found out it wrong.
At first I have not to do any thing in shell.
now I want change users password.I send the shell:

os.system("passwd %s" % username)

now shell wants me "Enter new password:" and i have to type it in shell.
but i have not do it.so i have to send the password in my code.but how can i do it?

Have a look at the command 'chpasswd'. With this you can set a password without shell usage.

sorry.I saw links but i can not solve my problem yet.
...
.but how can i do it?

You should really follow those links that woooee provided. For this type of task you should be either using pexpect or subprocess PIPES, not os.system .

Edited 6 Years Ago by jlm699: n/a

It worked.I forgot using the below code.

child.expect(pexpect.EOF, timeout=None)

Thanks alot.

This question has already been answered. Start a new discussion instead.