问题
>>> ssh_stuff
['yes/no', 'Password:', 'password', 'Are you sure you want to continue connecting']
>>> prompt
['$', '#']
>>> child = pexpect.spawn('ssh kumarshubham@localhost')
>>> child.expect(ssh_stuff)
1
>>> child.sendline(getpass.getpass())
Password:
11
>>> child.expect(prompt)
0
>>> child.sendline('ls -l')
6
>>> child.expect(prompt)
0
>>> print child.before, child.after
can one tell me why my child.before and after is empty, it should return directory listing.
回答1:
The expect
method takes a pattern or a list of patterns. These patterns are treated as regular expressions. This is maybe not so clear from the documentation, but if you look into the code of pexpect
, then you can see that it is the case.
The prompt variable is given as
prompt = ['$', '#']
The $
is a special character in regular expression, which will match according to python regex documentation:
'$' Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline.
We can see that it is the one being matched in the console output:
>>> child.expect(prompt)
0
To interpret the $
sign as a literal it must be preceded by a backslash.
prompt = ['\$', '#']
来源:https://stackoverflow.com/questions/40056626/pexpect-child-before-and-child-after-is-empty