效果預覽
服務端方法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框架搭建