如何在Python中通过SSH远程主机执行pbrun命令并自动输入密码?
解决pbrun切换root时自动输入密码的问题
你的问题在于exec_command是一次性执行命令的方式,无法处理需要交互输入的场景(比如pbrun执行后要求输入密码)。要实现自动输入密码,需要使用paramiko的invoke_shell创建交互式SSH会话,模拟手动输入命令和密码的流程。
以下是修改后的代码:
import time import paramiko output_file = 'paramiko.log' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接远程主机 ssh.connect('host', port=22, username='test', password='XXXXXXX') # 创建交互式shell会话 shell = ssh.invoke_shell() shell.settimeout(10) # 设置超时时间,避免无限等待 # 发送pbrun切换root的命令,末尾加\n模拟回车 shell.send('pbrun ohsoap -u root\n') time.sleep(0.5) # 等待主机返回密码提示 # 读取当前输出,确认密码提示出现(可选,更严谨的判断逻辑) current_output = shell.recv(65535).decode() if 'Password:' in current_output: # 发送pbrun密码,同样加\n模拟回车 shell.send('你的pbrun密码\n') time.sleep(0.5) # 可在此处发送需要root权限执行的后续命令,示例: # shell.send('whoami\n') # time.sleep(0.5) # 读取所有会话输出 full_output = shell.recv(65535).decode() print('log printing: ', full_output) # 将输出写入文件 with open(output_file, "w+") as file: file.write(full_output) # 关闭SSH连接 ssh.close()
关键说明:
- 用
invoke_shell替代exec_command,建立双向交互的会话通道,支持实时输入输出 - 发送命令和密码时必须追加
\n,模拟手动按下回车的操作 - 添加
time.sleep等待远程主机响应,也可以通过循环检测输出中的特定字符(比如"Password:")来替代固定延迟,提升脚本可靠性 - 如果需要执行多个root权限命令,可继续通过
shell.send()发送,每次发送后等待响应再读取输出
内容的提问来源于stack exchange,提问作者Randa Ahmed
相关产品推荐
相关产品推荐

