问题
I am using pexpect to upload a file to SFTP server. For accesssing the server first time, I get message as
The authenticity of host..can't be established.Are you sure you want to continue connecting (yes/no)?
to which I want the user to interact and answer yes/no. However, when user says yes, I want the interactive mode to be off and then take the password from my script instead of prompting user. Is this possible using pexpect ?
p = spawn('XXXXXXXX')
password = 'XXXXXXXXx'
out=p.expect(['(?i)password:', '(?i)Are you sure you want to continue connecting (yes/no)?']
if out == 1:
p.interact()
# Script should continue to send password and upload file
But this goes into interactive mode and doesn't come back to script
Pls. note - I run this python script in my terminal.
If not pexpect, pls.propose a solution not based on paramiko, pysftp
回答1:
Check the pexpect documentation:
interact(escape_character='\x1d', input_filter=None, output_filter=None)[source]
This gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed. This simply echos the child stdout and child stderr to the real stdout and it echos the real stdin to the child stdin. When the user types the escape_character this method will return None.
You can pass an escape character to p.interact()
, after which point interactive mode will be disabled. If all the user needs to type is yes
, then you could set the escape character to a
(or some other letter that doesn't appear in "yes" or "no"), like this:
p.interact('a')
来源:https://stackoverflow.com/questions/61560471/switch-between-interactive-and-non-interactive-mode-in-pexpect