gpt4 book ai didi

python - 如何在 python 中将 ssh 通过 ssh 代理与 ssh-agent 并行进行身份验证?

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:20 25 4
gpt4 key购买 nike

我有一个项目,需要通过 ssh 连接到大量服务器以频繁调用命令。我认为这可以在 python 脚本中实现,但是我的要求似乎消除了所有潜在的解决方案。我只能从中间堡垒服务器访问服务器,并且只能使用通过 ssh 代理转发的 ssh 公钥。因此我的要求是:

  • 并行 ssh,这样我就不必等待数小时才能在所有服务器上完成命令
  • ssh 公钥支持,因为我无法使用密码身份验证
  • ssh 代理支持,因为我无法在不通过 ssh 代理服务器的情况下直接 ssh 到服务器
  • ssh 代理支持,因为我需要将我的(预加载的)ssh 公钥通过代理服务器发送到服务器

paramiko 似乎提供了除第一个要求(并行 ssh 支持)之外的所有内容。我发现了一个并行 ssh 模块 ( https://github.com/pkittenis/parallel-ssh ),它充当 paramiko 的薄包装器,但可惜的是,除了并行 ssh 和公钥身份验证之外,它似乎缺乏对几乎所有内容的 API 支持。

这是我现在所拥有的,它可以在一些不需要代理或 ssh-agent 访问的本地服务器上运行:

#!/usr/bin/python2.7

import sys
if 'threading' in sys.modules:
raise Exception('threading module loaded before patching!')
import gevent.monkey; gevent.monkey.patch_thread()
import paramiko
from pssh import ParallelSSHClient

paramiko.util.log_to_file("filename.log")
hosts = ['ocb100','netllama']
client_key = paramiko.DSSKey.from_private_key_file('/home/netllama/.ssh/id_dsa')
client = ParallelSSHClient(hosts, pkey=client_key)

cmds = client.exec_command('uptime')

最佳答案

您之前提到的parallel-ssh模块可以满足您的要求。专门用于代理和代理转发:

  • SSH 代理支持 - native 代理和隧道支持,也是异步的
  • SSH 代理转发 - 默认启用。 forward_ssh_agent=True 创建 ParallelSSH 对象。

使用 ParallelSSH 的示例:

from pssh import ParallelSSHClient
hosts = ['ocb100','netllama']
client = ParallelSSHClient(hosts, proxy_host='bastion')
output = client.run_command('uptime')
for host in output:
for line in output[host]['stdout']:
print(line)

执行上述操作的用户的 SSH key 会从正在运行的 SSH 代理自动加载,您无需指定 pkey 参数。

如果您需要更改登录用户,可以设置 user 参数,例如 ParallelSSHClient(hosts, user='netllama')

根据 this issue 于 9 月 4 日向 ParallelSSH 添加了 SSH 代理转发支持.

ParallelSSH 已经使用 gevent 根据文档异步执行所有网络请求,它不使用线程或多处理,例如与 Fabric 不同。因此,您也不需要这些 gevent 导入。

ParallelSSH 的文档是 here .

编辑:更新为最新的库 API

关于python - 如何在 python 中将 ssh 通过 ssh 代理与 ssh-agent 并行进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25576275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com