我是python和django的新手,Ian使用paramiko模块获取服务器cpu利用率,我想在我的html模板中呈现该输出。我可以用html打印单个服务器的输出。
但我无法在html模板中打印多个服务器输出。
实施例: - 我有100台服务器,一旦登录我的网页,我想获得所有服务器的cpu利用率。
我正在使用带有主机名和IP的CSV文件。
在我的views.py中,我使用looop来读取CSV文件中的ips。通过使用paramiko模块,我得到输出。
我正在使用以下请求。
Views.py
For loop
return render(request, 'personal/welcome.html', {'host':[hostname],'cpu':[cpu]} )
在我的html模板中
{{host}} {{cpu}}
但我只能打印CSV文件中最后一个服务器输出。
请告诉我有没有其他方法可以打印所有服务器输出,或者我可以将所有服务器输出保存在文本文件中。并将其打印在同一网页上。
----- views.py
if user.is_active:
# If the account is valid and active, we can log the user in.
# We'll send the user back to the homepage.
with open('E:\ips.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
print(readCSV)
for row in readCSV:
a = row[1]
b = row[0]
ip = a
host=b
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh_client.connect(ip, username='username', password='password)
output = ""
stdin, stdout, stderr = ssh_client.exec_command("uname")
uname = stdout.readlines()
ssh_client.close()
for line in uname:
output = output + line
if output != "":
status="online"
else:
status="offline"
login(request, user)
return render(request,'personal/welcome.html',{'status':[status])
------ welcome.html
<i></i> HOSTNAME IP_ADDR LIVE_STATUS RAM_FREE(GB)
</address>
</li>
</ol>
{% block content %}
{% for status in status %}
<I></I>{{status}}
{% endfor %}
% endblock %}
<!--<div id="morris-area-chart"></div> -->
答案 0 :(得分:0)
您错过了一个相当基本的概念,即为了收集多个值,您需要使用某种容器,例如列表。我真的不明白你在该代码中想要做什么,但似乎你想要一个状态列表。所以,像:
statuses = []
for row in readCSV:
...
if output != "":
statuses.append("online")
else:
statuses.append("offline")
return render(request,'personal/welcome.html',{'statuses': statuses)
并在模板中:
{% for status in statuses %}
<i>{{status}}</i>
{% endfor %}