【问题标题】:Python: asynchronically ssh to multiple servers and execute commands, then save result into databasePython:异步ssh到多个服务器并执行命令,然后将结果保存到数据库中
【发布时间】:2021-06-21 14:23:36
【问题描述】:

我在 Google 和 stackOverflow 上进行了广泛搜索,但找不到相关答案。所以在这里问。希望您可以演示如何做到这一点。

我的用例如下:

  1. 用户在 django 表单字段中输入 IP 地址(例如 12.12.12.12、13.13.13.13、14.14.14.14)
  2. django 获取这些机器的 ips 和 ssh 并执行预定义的脚本
  3. 如果脚本运行成功,则 django 将结果保存到数据库中
  4. django显示每个服务器的执行结果(成功,失败)

我可以使用同步方法实现上述功能,但是等待时间长得令人难以忍受。尝试使用 asyncio.run 来改进它,但反复尝试并失败。 :S 这是我的代码:

在views.py中

def create_record(request):
    record_form = RecordForm()

    if request.method == 'POST':
        record_form = RecordForm(request.POST)
        if record_form.is_valid():
            ips = record_form.cleaned_data['ip'].split(',') 
            start_time = time.time()
            for ip in ips:
                record_form = RecordForm(request.POST)
                record = record_form.save(commit=False)
                record.ip = ip
                record = asyncio.run(run_script(record))  # this function ssh to server and execute commands
                if record is correct:
                    record.save()
                    messages.success(request, ip + ' execution success')
                else:
                    messages.error(request, ip + ' execution failed')
            total = time.time() - start_time
            print('total:', total)
            return redirect('create_record') 
    context = {'record_form': record_form}
    return render(request, 'record-form.html', context)

run_script 如下:

async def run_script(record):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        client.connect(record.ip, username='xxx', pass)
        ssh_stdin, ssh_stdout, ssh_stderr = await client.exec_command('{script.sh}')  #python complains await cannot be used here
        # process output
        for line in ssh_stdout:
            info = line.strip('\n')
    except Exception as e:
        print("Exception: ", e)

    client.close()
    record.info = info
    return record

【问题讨论】:

    标签: python-3.x django async-await python-asyncio


    【解决方案1】:

    我现在查看了 Paramiko,但找不到任何异步功能。 https://github.com/paramiko/paramiko/pull/68 从 2012 年开始,他们没有接受拉取请求

    我认为 AsyncSSH 可能是最好的解决方案。你试过了吗?

    【讨论】:

    • 谢谢你的建议,我试试看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2023-03-16
    相关资源
    最近更新 更多