Python:异步ssh到多个服务器并执行命令,然后将结果保存到数据库中



我在谷歌和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这是我的代码:

视图.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

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

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

相关内容

最新更新