0

I want to run the shell command 'su - testuser -c "id"' and get the output. In the console it asks the password after that. My intention is to run it in a python script where it logs into antoher user (neither the source nor the destination user has root rights). The problem is, that the password should be entered non-interactive, so that I can just start the script and see the output without entering the password. So I can start the python script and it automatically runs the command without waiting for the password and gives me the output.

I tried it using the pexpect package:

child = pexpect.spawn('su - testuser -c "id"') 
child.expect_exact('Password:')
child.sendline('mypassword')
print(child.before) # Prints the output of the "id" command to the console

The problem is that the code doesn't function. The output is like a random string instead of the id and so on. How can I do that?

orcam2000
  • 43
  • 1
  • 1
  • 3

1 Answers1

1

Using child.read instead of print(child.before) solves it.

>>> child = pexpect.spawn('su - testuser -c "id"') 
>>> child.expect_exact('Password:')
0
>>> child.sendline('1234')
5
>>> print(child.before)
b''
>>> child.read()
b' \r\nuid=1002(testuser) gid=1003(testuser) groups=1003(testuser)\r\n'

You can read more details on here

Shahar Glazner
  • 377
  • 4
  • 10
  • Thank you, now it works. But how can I print for commands that create the output step by step? E.g. for an installation, the full output text isn't there instantly. I tried it using "startsap" for starting a sap system and the child.read() fails. It only works for commands that write get the output instantly like "I'd", "pwd" "ls" "whoami" and so on. – orcam2000 Feb 02 '21 at 13:09
  • Can you add an example of what you are trying to do? – Shahar Glazner Feb 02 '21 at 13:25
  • Now it works. It was the default timeout of pexpect that is too small. I changed that by adding "child.timeout=300" (default is 30). – orcam2000 Feb 02 '21 at 15:57