简体   繁体   中英

pexpect: howto dump all content from child “as is”?

We have some strange setup on our "shared" server that will not remember my git password for certain situations. I tried hard to fix the real issue; but at some point I gave up and created this python script:

#!/usr/bin/env python3
"""
pass4worder: a simply python script that runs a custom command; and "expects" that command to ask for a password.
The script will send a custom password - until the command comes back with EOF.
"""

import getpass
import pexpect
import sys

def main():
    if len(sys.argv) == 1:
      print("pass4worder.py ERROR: at least one argument (the command to run) is required!")
      sys.exit(1)

    command = " ".join(sys.argv[1:])
    print('Command to run: <{}>'.format(command))
    password = getpass.getpass("Enter the password to send: ")

    child = pexpect.spawn(command)
    print(child.readline)
    counter = 0

    while True:
        try:
            expectAndSendPassword(child, password)
            counter = logAndIncreaseCounter(counter)
        except pexpect.EOF:
            print("Received EOF - exiting now!")
            print(child.before)
            sys.exit(0)


def expectAndSendPassword(child, password):
    child.expect("Password .*")
    print(child.before)
    child.sendline(password)


def logAndIncreaseCounter(counter):
    print("Sent password ... count: {}".format(counter))
    return counter + 1

main()

This solution does the job; but I am not happy about how those prints look like; example:

> pass4worder.py git pull
Command to run: <git pull>
Enter the password to send: 
<bound method SpawnBase.readline of <pexpect.pty_spawn.spawn object at 0x7f6b0f5ed780>>
Received EOF - exiting now!
b'Already up-to-date.\r\n'

I would rather prefer something like:

Already up-to-date
Received EOF - exiting now!

In other words: I am looking for a way so that pexect simply prints everything "as is" to stdout ... while still doing its job.

Is that possible?

(any other hints regarding my script are welcome too)

  1. child.readline is a function so I think you actually wanted print(child.readline() ) .
  2. Change print(child.before) to print(child.before.decode() ) . bytes.decode() converts bytes ( b'string' ) to str .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM