'Change user (su) via Python script (pexpect, popen...)

I am running a Python script with user1 and in this script I need to move a file in a folder for which I don't have access. The folder is owned by user2.

What I want to do is :
- change from user1 to user2 using su - user2
- enter the password
- move the file

So far I tried with Popen :

p = subprocess.Popen(["su", "-", "user2"])
p.communicate("user2_password")
p.communicate("mv path/to/file other/path/to/file")

It doesn't work, I need to manually enter the password in the shell.


And I also tried with pexpect :

child = pexpect.spawn('su - user2')
child.expect ('Password:')
child.sendline('user2_password')
child.sendline('mv path/to/file other/path/to/file')

The script runs but nothing happens and after running the script I'm still user1.

Any idea why ? For what it's worth, it seems to be specific to su because if I write a script with sudo it works (I can feed the password).

Thank you for your help !



Solution 1:[1]

Your command fails as you do not expect anything after sending the password. Depending on your shell etc, you will get some kind of a command prompt after a successful su. My prompt is this:

klunssi@xyzzy:~$

In fact printing that prompt includes many special characters to control tty output, so I just want to grab the trailing $:

child = pexpect.spawn('su - klunssi')
child.expect ('Password:')
child.sendline('klunssi')
child.expect('\$')
child.sendline('mv /home/klunssi/foo /home/klunssi/bar')

This works and does the move.

It does not leave me with "klunssi" account as pexpect.spawn() creates a subprocess and su happens there.

If you have root access to the system, I suggest modifying /etc/sudoers and adding a passwordless sudo so that your user1 can run commands as user2. This is far more reliable as you do not need pexpect at all and can just

Popen(["sudo", "-u", "user2", "yourcommand"])

If this is not an option, then the above pexpect should do the trick.

Hannu

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1