pexect - unable to catch EOF

Viewed 158

I am unable to get EOF output for pexpect.

import pexpect

session = pexpect.spawn('scp -C -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -r /tmp/test abcuser@x.x.x.x:/tmp', encoding='utf-8')
session.expect(pexpect.EOF, timeout=None)

[CTRL + C ] - After waiting for long

^CTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/pexpect/spawnbase.py", line 340, in expect
    return self.expect_list(compiled_pattern_list,
  File "/usr/lib/python3/dist-packages/pexpect/spawnbase.py", line 369, in expect_list
    return exp.expect_loop(timeout)
  File "/usr/lib/python3/dist-packages/pexpect/expect.py", line 111, in expect_loop
    incoming = spawn.read_nonblocking(spawn.maxread, timeout)
  File "/usr/lib/python3/dist-packages/pexpect/pty_spawn.py", line 470, in read_nonblocking
    r, w, e = select_ignore_interrupts(
  File "/usr/lib/python3/dist-packages/pexpect/utils.py", line 143, in select_ignore_interrupts
    return select.select(iwtd, owtd, ewtd, timeout)
KeyboardInterrupt
1 Answers

I set up a quick internal network using two VM's, and when I ran the scp command at the prompt, I saw:

Warning: Permanently added '192.168.56.101' (RSA) to the list of known hosts.
abcuser@192.168.56.101's password: 

To provide a password (if asked) and to get your feedback, I would modify the code to:

import pexpect
from getpass import getpass

session = pexpect.spawn(
    "scp -C -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -r /tmp/test abcuser@192.168.56.101:/tmp",
    encoding="utf-8")
     
# EOF = Command finished executing and the child is closed
index = session.expect_exact(["password:", pexpect.EOF])

# First feedback
print(str(session.before) + str(session.match) + "\n")

if index == 0:
    password = getpass()
    session.sendline(password)
    session.expect_exact(pexpect.EOF)

# Final feedback; the match is EOF and there is nothing after that
print(str(session.before))

# The child is already closed, but just in case
session.close()

Output

Warning: Permanently added '192.168.56.101' (RSA) to the list of known hosts.
abcuser@192.168.56.101's password:

Password: 
 
test                                          100%   16    36.7KB/s   00:00

I would avoid setting timeout to None. Either use the default 30 seconds or set a reasonable time limit for larger files.

Hope this is what you were looking for. Good luck coding!

Related