Python+Kivy搭建SSH隧道时,如何自动输入SSH密码?
解决SSH隧道自动输入密码的问题
你原来的方法无效的核心原因是:
os.system()会阻塞等待命令执行完毕才返回,返回值是命令的退出码(整数),不是命令的输出内容,所以用startswith()判断完全不成立。- 就算能捕获输出,
os.system()也无法和运行中的子进程交互输入内容。
方案一:使用subprocess模块实现交互
用subprocess.Popen启动SSH进程,通过管道和子进程交互,实时检测输出并输入密码:
import subprocess connect_command = ["ssh", "-vND", "port", "user@my-server-ip"] password = "something-got-from-user-input" # 启动SSH进程,开启管道用于输入输出交互 process = subprocess.Popen( connect_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, # 把stderr合并到stdout,方便统一监听 text=True ) # 循环读取输出,检测密码提示 while True: output_line = process.stdout.readline() if not output_line: break # 进程结束,退出循环 # 检测到密码提示时,写入密码 if "user@my-server-ip's password:" in output_line: process.stdin.write(password + "\n") process.stdin.flush() # 强制刷新缓冲区,确保密码发送出去 # 等待进程结束并获取退出码 return_code = process.wait()
方案二:使用pexpect模块(更简洁)
pexpect是专门处理交互式命令行的库,使用起来更直观,但需要先安装:pip install pexpect
import pexpect connect_command = "ssh -vND port user@my-server-ip" password = "something-got-from-user-input" # 启动进程并等待密码提示 child = pexpect.spawn(connect_command) child.expect("user@my-server-ip's password:") # 发送密码 child.sendline(password) # 保持进程运行并输出内容 child.interact()
额外建议
- 不要硬编码密码,通过Kivy的输入框安全获取用户输入。
- 更安全的方式是使用SSH密钥对登录:生成密钥对后将公钥放到服务器的
~/.ssh/authorized_keys中,后续SSH连接无需输入密码。
内容的提问来源于stack exchange,提问作者kodfire
相关产品推荐
相关产品推荐

