Python paramiko 如何输入交互式密码?

要对华为的 IBMC 更改密码,官方文档只给了这么一个流程 Fr1TgA.jpg

https://s1.ax1x.com/2018/12/20/Fr1TgA.jpg

搜索了下交互输入就只有这个 s.exec_command('su -root') stdin.write('password') stdin.flush()

自己参考改了就是各种没反应... 或者报错

求教


Python paramiko 如何输入交互式密码?

12 回复

下班跑路顺手顶一下


paramiko 处理交互式密码,最直接的方式是使用 invoke_shell() 配合 send() 方法。不过,更推荐用 exec_command() 配合 get_pty=True 来模拟终端,然后用标准输入写入密码。

这里有个例子,假设你要 sudo 一个命令:

import paramiko
import time

def ssh_interactive_password(hostname, username, password, sudo_password, command):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        # 1. 建立SSH连接
        client.connect(hostname, username=username, password=password)
        
        # 2. 获取交互式shell通道
        channel = client.invoke_shell()
        
        # 3. 发送sudo命令
        channel.send(f"sudo {command}\n")
        
        # 4. 等待密码提示(这里简单用sleep,生产环境建议用正则匹配提示)
        time.sleep(1)
        
        # 5. 发送sudo密码
        channel.send(f"{sudo_password}\n")
        
        # 6. 等待命令执行完成
        time.sleep(2)
        
        # 7. 读取输出
        output = ""
        while channel.recv_ready():
            output += channel.recv(1024).decode('utf-8')
        
        print("命令输出:", output)
        
    finally:
        client.close()

# 使用示例
ssh_interactive_password(
    hostname="your_host",
    username="your_username",
    password="your_ssh_password",  # SSH登录密码
    sudo_password="your_sudo_password",  # sudo密码
    command="ls -la /root"
)

关键点:

  • invoke_shell() 创建交互式会话
  • send() 发送命令和密码
  • time.sleep() 给系统响应时间(实际项目建议用正则匹配提示符)
  • 记得处理编码和可能的错误

如果只是执行单个命令,用 exec_command() 配合 get_pty=True 会更简洁:

stdin, stdout, stderr = client.exec_command(f"sudo {command}", get_pty=True)
stdin.write(f"{sudo_password}\n")
stdin.flush()
print(stdout.read().decode())

invoke_shell 更灵活,但 exec_command 更简单。根据你的交互复杂度选就行。

简单说就是:开个shell通道或者伪终端,直接往里写密码字符串。

pyexpect

调 shell 用 sshpass

谢楼上各位,明天试试

少个\n 吧…

你说的这可能性我也试了,凉凉

passwd 修改密码可以这样,你可以参照修改下试试
stdin, stdout, stderr = ssh_client.exec_command(“passwd”, timeout = 10)
stdin.write("{0}\n{1}\n{1}\n".format(old_password, new_password))
out,err = stdout.read(),stderr.read()

好的,我明天测试

可以试试 fabric,又 watcher,可以类似 pexpect 进行正则匹配后输入信息

现在还没涉及到你所说的功能…能输入就 ko 了

stdin 和 tty 不同的
ssh 是从 tty 读取密码的

萌新不太清楚这个,学习了

回到顶部