We can create mockup.py that will be a stand-in for whatever program you are trying to control:
import getpass
hostname = input('System address: ')
username = input('Username: ')
password = getpass.getpass('Password: ')
if password == 'good_guess':
while True:
line = input('mockup> ')
if line == 'quit':
break
Sample Interaction
$python mockup.py
System address: bogus
Username: nobody
Password:
mockup> fake command
mockup> quit
We can write a Python program that will control mockup.py and log all interaction to a file named session.log:
import pexpect
import getpass
hostname = input('hostname: ')
username = input('username: ')
password = getpass.getpass('password: ')
prompt = 'mockup> '
with open('session.log', 'wb') as log_file:
session = pexpect.spawn('python3 mockup.py')
session.expect_exact('System address: ')
session.sendline(hostname)
session.expect_exact('Username: ')
session.sendline(username)
session.expect_exact('Password: ')
session.sendline(password)
# Start logging to a file here
session.logfile_read = log_file
session.expect_exact(prompt)
session.sendline('fake command')
session.expect_exact(prompt)
session.sendline('quit')
session.expect_exact(pexpect.EOF)
Sample Interaction
$ python3 use_pexpect.py
hostname: bogus
username: nobody
password:
Contents of session.log
mockup> fake command
mockup> quit
This should be enough information to get you started.