【发布时间】:2021-06-21 14:23:36
【问题描述】:
我在 Google 和 stackOverflow 上进行了广泛搜索,但找不到相关答案。所以在这里问。希望您可以演示如何做到这一点。
我的用例如下:
- 用户在 django 表单字段中输入 IP 地址(例如 12.12.12.12、13.13.13.13、14.14.14.14)
- django 获取这些机器的 ips 和 ssh 并执行预定义的脚本
- 如果脚本运行成功,则 django 将结果保存到数据库中
- 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