使用Python Paramiko实现SSH登录时自动输入yes及密码的问题
解决SSH登录时需先确认yes再输入密码的自动化问题
你的问题出在paramiko.connect()方法无法处理登录过程中额外的交互式确认步骤(即输入用户名后需要先回复yes才能进入密码输入环节)。要实现这种流程,需要使用paramiko的交互式shell会话,手动处理每一步的输入输出。
以下是修改后的代码:
import paramiko import time ip_address = "1.1.1.1" username = "abc" password = "1234" show_commands = ["show interfaces", "show routing table", "show system info"] ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 建立SSH连接,仅传入用户名,暂不传入密码 ssh.connect(hostname=ip_address, username=username, password=None, look_for_keys=False, allow_agent=False) # 启动交互式shell会话 shell = ssh.invoke_shell() shell.settimeout(10) # 设置超时,避免无限等待 # 等待确认提示并发送yes while True: if shell.recv_ready(): output = shell.recv(1024).decode() if "Do you accept and acknowledge the statement above ? (yes/no) :" in output: shell.send("yes\n") break time.sleep(0.5) # 等待密码提示并发送密码 while True: if shell.recv_ready(): output = shell.recv(1024).decode() if "Password:" in output or "password:" in output: shell.send(f"{password}\n") break time.sleep(0.5) # 等待登录成功后的提示符(根据服务器实际提示符调整,比如'>'或'#') while True: if shell.recv_ready(): output = shell.recv(1024).decode() if ">" in output or "#" in output: break time.sleep(0.5) # 逐条执行命令并获取输出 for command in show_commands: shell.send(f"{command}\n") time.sleep(1) # 等待命令执行完成,可根据服务器响应速度调整时长 output = "" while shell.recv_ready(): output += shell.recv(1024).decode() print(f"Output of '{command}':") print(output) print("-" * 50) ssh.close()
关键说明:
- 连接时不直接传入密码,改用交互式shell手动处理确认和密码输入流程
- 通过
recv_ready()检查服务器输出状态,避免程序阻塞 - 加入
time.sleep()等待服务器响应,时长可根据实际情况调整 - 需等待登录成功后的提示符出现,再执行后续命令,确保命令能被正确识别
内容的提问来源于stack exchange,提问作者Tarun Gupta
相关产品推荐
相关产品推荐

