python 如何通过 SSH 连接自动回答提示

How to auto answer prompts via SSH connection in python

我想使用 python paramiko 调用远程机器上的应用程序;此应用程序会等到您输入特定的字符串,然后才会成功。如何通过 SSH 连接向它发送请求的字符串?

应用程序调用如下:

./app --init

This option will delete the database and recreate all files.
OLD DATA (IF ANY) WILL BE LOST!

This option must be used just on one of your servers.
Running it on any one of the servers will delete the other server's data, too.
If you are sure, type the following sentence and press ENTER:

I KNOW THAT THIS OPTION DESTROYS EVERYTHING; DO IT ANYWAY.

然后我应该输入 I KNOW THAT THIS OPTION DESTROYS EVERYTHING; DO IT ANYWAY. 并按 ENTER 继续。

我有这个连接到远程主机的代码:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=usrname, password=passwd, compress=True)

我试过了self.sshlink.exec_command('cd app_addr;./app --init');它什么也没做。

我在 this question 中的一个未被接受的答案中找到了解决方案。

这是我最终尝试并成功的:

cmd = 'cd app_address;./app --init'
answer = 'I KNOW THAT THIS OPTION DESTROYS EVERYTHING; DO IT ANYWAY.'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)
ssh_stdin.write(answer + '\n')
ssh_stdin.flush()
time.sleep(5)
ssh_stdout.read()