Django实现环境实时监控功能

bktest 2019-10-21

效果预览

Django实现环境实时监控功能

 服务端方法getEnvinfo接口开发

1.依赖包安装(ssh协议工具包)

pip install paramiko

2.主机配置

host = {‘ip‘: ip, ‘port‘: port, ‘username‘: username, ‘password‘: password}

3.远程执行命令并获取返回结果

#打开ssh客户端
ssh = paramiko.SSHClient()
# 设置为接受不在known_hosts 列表的主机可以进行ssh连接
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host[‘ip‘], port=host[‘port‘], username=host[‘username‘], password=host[‘password‘])
#获取内存信息
stdin, stdout, stderr = ssh.exec_command(‘sudo free -m|grep Mem‘)
str_out = stdout.read().decode()
totalmem = str(str_out).split("      ")[1].replace(" ","")
freemem = str(str_out).split("      ")[2].replace(" ","")
ram_usage = str(int(freemem)/int(totalmem)*100).split(".")[0]+"%"
#获取cpu信息
stdin, stdout, stderr = ssh.exec_command(‘top -bn 1 -i -c|grep us|grep id‘)
str_out = str(stdout.read().decode()).replace(" ","")
cpu_usage = str(100-int(str_out.split(",")[3].split(".")[0]))+"%"
#获取磁盘信息
stdin, stdout, stderr = ssh.exec_command(‘df -h|grep G |grep -o [0-9]*%|grep [0-9][0-9]‘)
str_out = stdout.read().decode()
rom_usage = str(str_out).replace("\n","")
#关闭ssh客户端
ssh.close()

4.封装并返回环境信息

env_info={‘host‘:host[‘ip‘],‘ramusage‘:ram_usage,‘cpuusage‘:cpu_usage,‘romusage‘:rom_usage}
return env_info

5.前端动态请求回显

$(function () {
    function getenvinfo(ip){
        if (ip.length>8){
            $.ajax({
                type:‘GET‘,
                url:‘http://localhost:8000/getEnvinfo‘,
                data:{
                    ip:ip
                },
                success:function (result) {
                    console.log(result)
                    $(‘#cpuusage‘).find("span")[0].textContent=result.cpuusage
                    $(‘#cpuusage‘).attr("style","width: "+result.cpuusage)
                    $(‘#romusage‘).find("span")[0].textContent=result.romusage
                    $(‘#romusage‘).attr("style","width: "+result.romusage)
                    $(‘#ramusage‘).find("span")[0].textContent=result.ramusage
                    $(‘#ramusage‘).attr("style","width: "+result.ramusage)
                },
                error:function (e) {
                    console.log(e.status);
                }
            });
        }
    }
    $(‘#ip‘).on(‘blur‘,function (){
        getenvinfo($(this).val())
    });
    $(‘#ip‘).keyup(function(event){
        if(event.keyCode ==13){
            getenvinfo($(this).val())
        }
    });
    setInterval(function (){
        getenvinfo($(‘#ip‘).val())
    },90000)
}); 

基于Django框架搭建

相关推荐

inspuryhq / 0评论 2020-07-28