2

I would like to capture a ssh password prompt as string in python. For example:

> ssh user@hostname
user@hostname's password:

I need this string 'user@hostname's password:'. A similar question is asked here. I tried to use subprocess and paramiko, but I didn't manage to capture the string. Is there anyway to get it?

LetsOMG
  • 429
  • 1
  • 5
  • 11

2 Answers2

0

[Solved]

Solved with pexpect. I can read this data from pexpect.spawn. A advantage of pexpect is that, by using interact() method, I can give back control to the interactive user (the human at the keyboard) after program processes the login, which is exactly what I want.

I can fetch the string 'user@hostname's password:' using this method. However, if I want to give the interactive user control after login, it seems complicated.

LetsOMG
  • 429
  • 1
  • 5
  • 11
0

Although OP already answered this question, I believe sharing some actual Python code - based on pexec, as described in the accepted answer - will be useful:

import pexpect

child = pexpect.spawn("ssh user@localhost")
child.expect(".+") # Greedy match on everything that follows
print("Captured:", child.match.group(0))

The key part from pexpect.expect()'s documentation:

When a match is found for the given pattern, the class instance attribute match becomes an re.MatchObject result.

buherator
  • 111
  • 3