目的:利用ansible检查后端服务器数据每天备份情况
平台:Django
1.views.py 中添加函数
import subprocess
import shlex
def backup_status(request):
arg_mysql = "du -sh /backup/mysql/db/`date -I`"
arg_mongo = "du -sh /backup/mongodb/`date -I`"
arg_data = 'tail -n 3 /var/log/rsync_data.`date +"%Y%m%d2301" -d"-1day"`'
cmd_mysql = "/usr/bin/ansible 192.168.1.1 -m raw -a '%s'" % arg_mysql
cmd_mongo = "/usr/bin/ansible 192.168.1.3 -m raw -a '%s'" % arg_mongo
cmd_data = "/usr/bin/ansible 192.168.1.3 -m raw -a '%s'" % arg_data
results = ()
for cmd in (cmd_mysql, cmd_mongo, cmd_data):
#将标准输出和错误输出放在一起,直接返回output
process = subprocess.Popen(shlex.split(cmd),stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = process.communicate()[0]
s=(output,)
results += s
status = {}
keys = ('mysql','mongo','data')
# 将结果整合为字典,以json格式返回给前端,
for key,value in zip(keys,results):
status[key] = value
return HttpResponse(json.dumps(status), content_type='application/json')
2.前端模板添加jquery
<script type="text/javascript"> function backup_status(){ $.ajax({ url:'/backup_status/', beforeSend: function(){ $("#loading").html("<img src='/static/img/loading.gif' />"); }, success: function(status){ $("#mysql").html(status.mysql); $("#mongo").html(status.mongo); $("#data").html(status.data); }, complete:function(){ $("#loading").html("") } }); }; </script>
3. urls.py 配置
url(r'^backup_status/$', 'backup_status'),
4.逻辑
页面上点击button的时候,会触发函数backup_status,返回数据;由于后端ansible获取数据时间较长,因此,在数据返回之前即ajax的beforeSend状态添加loading提示图片,ajax请求结束后 隐藏图片
转载于:https://blog.51cto.com/3379770/1906357