最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解用Python實(shí)現(xiàn)自動(dòng)化監(jiān)控遠(yuǎn)程服務(wù)器

 更新時(shí)間:2019年05月18日 15:22:17   作者:代碼幫  
這篇文章主要介紹了用Python實(shí)現(xiàn)自動(dòng)化監(jiān)控遠(yuǎn)程服務(wù)器,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

最近發(fā)現(xiàn)Python課器做很多事情,在監(jiān)控服務(wù)器有其獨(dú)特的優(yōu)勢(shì),耗費(fèi)資源少,開(kāi)發(fā)周期短。

首先我們做一個(gè)定時(shí)或者實(shí)時(shí)腳本timedtask.py,讓其定時(shí)監(jiān)控目標(biāo)服務(wù)器,兩種方式:

第一種:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time  : 2017/11/27 15:59
# @Desc  : 定時(shí)任務(wù),以需要的時(shí)間間隔執(zhí)行某個(gè)命令
# @File  : timedtask.py
# @Software: PyCharm
 
import time, os
from monitorserver import alltask
 
 
def roll_back(cmd, inc = 60):
  while True:
    #執(zhí)行方法,函數(shù)
    alltask()
    time.sleep(inc)
 
roll_back("echo %time%", 5)

第二種:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time  : 2017/11/27 15:59
# @Desc  : 定時(shí)任務(wù),以需要的時(shí)間間隔執(zhí)行某個(gè)命令
# @File  : timedtask.py
# @Software: PyCharm
 
import time, os
 
def roll_back(cmd, inc = 60):
  while True:
    #監(jiān)控代碼文件所在位置
    os.system('python /home/../monitorserver.py');
    time.sleep(inc)
 
roll_back("echo %time%", 5)

做過(guò)監(jiān)控應(yīng)該都知道,我們主要監(jiān)控服務(wù)器,負(fù)載均衡、磁盤(pán)、內(nèi)存、CPU、網(wǎng)絡(luò)接口(流量)、端口代碼,主要針對(duì)這些,我做了以下遠(yuǎn)程監(jiān)控,第一種和第二種監(jiān)控代碼一樣,代碼monitorserver.py如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time  : 2017/11/27 15:59
# @Desc  : 服務(wù)器監(jiān)控代碼
# @File  : monitorserver.py
# @Software: PyCharm
 
import pexpect
import re
 
import time
import threading
 
"""
主方法
127.0.0.1#遠(yuǎn)程服務(wù)器ip地址
"""
def ssh_command(user, host, password, command):
  ssh_new_key = 'Are you sure you want to continue connecting'
  child = pexpect.spawn('ssh -l %s %s %s' % (user, host, command))
  i = child.expect([pexpect.TIMEOUT, ssh_new_key, 'password: '])
  if i == 0:
    print 'ERROR!'
    print 'SSH could not login. Here is what SSH said:'
    print child.before, child.after
    return None
  if i == 1:
    child.sendline('yes')
    child.expect('password: ')
    i = child.expect([pexpect.TIMEOUT, 'password: '])
    if i == 0:
      print 'ERROR!'
      print 'SSH could not login. Here is what SSH said:'
      print child.before, child.after
      return None
  child.sendline(password)
  return child
 
 
"""
內(nèi)存監(jiān)控
"""
def mem_info():
 
  child = ssh_command("遠(yuǎn)程服務(wù)器用戶名", "127.0.0.1", "遠(yuǎn)程服務(wù)器密碼", "cat /proc/meminfo")
  child.expect(pexpect.EOF)
  mem = child.before
  mem_values = re.findall("(\d+)\ kB", mem)
  MemTotal = mem_values[0]
  MemFree = mem_values[1]
  Buffers = mem_values[2]
  Cached = mem_values[3]
  SwapCached=mem_values[4]
  SwapTotal = mem_values[13]
  SwapFree = mem_values[14]
  print '******************************內(nèi)存監(jiān)控*********************************'
  print "*******************時(shí)間:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "******************"
  print "總內(nèi)存:",MemTotal
  print "空閑內(nèi)存:", MemFree
  print "給文件的緩沖大小:",Buffers
  print "高速緩沖存儲(chǔ)器使用的大小:", Cached
  print "被高速緩沖存儲(chǔ)用的交換空間大小:", SwapCached
  print "給文件的緩沖大小:", Buffers
  if int(SwapTotal) == 0:
    print u"交換內(nèi)存總共為:0"
  else:
    Rate_Swap = 100 - 100*int(SwapFree)/float(SwapTotal)
    print u"交換內(nèi)存利用率:", Rate_Swap
  Free_Mem = int(MemFree) + int(Buffers) + int(Cached)
  Used_Mem = int(MemTotal) - Free_Mem
  Rate_Mem = 100*Used_Mem/float(MemTotal)
  print u"內(nèi)存利用率:", str("%.2f" % Rate_Mem), "%"
 
 
"""
內(nèi)核線程、虛擬內(nèi)存、磁盤(pán)、陷阱和 CPU 活動(dòng)的統(tǒng)計(jì)信息
"""
def vm_stat_info():
  child = ssh_command("遠(yuǎn)程服務(wù)器用戶名", "127.0.0.1", "遠(yuǎn)程服務(wù)器密碼", "vmstat 1 2 | tail -n 1")
  child.expect(pexpect.EOF)
  vmstat_info = child.before.strip().split()
  processes_waiting = vmstat_info[0]
  processes_sleep = vmstat_info[1]
  swpd = vmstat_info[2]
  free = vmstat_info[3]
  buff = vmstat_info[4]
  cache = vmstat_info[5]
  si = vmstat_info[6]
  so = vmstat_info[7]
  io_bi = vmstat_info[8]
  io_bo = vmstat_info[9]
  system_interrupt = vmstat_info[10]
  system_context_switch = vmstat_info[11]
  cpu_user = vmstat_info[12]
  cpu_sys = vmstat_info[13]
  cpu_idle = vmstat_info[14]
  cpu_wait = vmstat_info[15]
  st=vmstat_info[16]
  print '****************************內(nèi)核線程、虛擬內(nèi)存、磁盤(pán)、陷阱和 CPU 活動(dòng)的統(tǒng)計(jì)信息監(jiān)控****************************'
  print "*******************時(shí)間:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "******************"
  print "等待運(yùn)行進(jìn)程的數(shù)量:", processes_waiting
  print "處于不間斷狀態(tài)的進(jìn)程:", processes_sleep
  print "使用虛擬內(nèi)存(swap)的總量:", swpd
  print "空閑的內(nèi)存總量:", free
  print "用作緩沖的內(nèi)存總量:", buff
  print "用作緩存的內(nèi)存總量:", cache
  print "交換出內(nèi)存總量 :", si
  print "交換入內(nèi)存總量 :", so
  print "從一個(gè)塊設(shè)備接收:", io_bi
  print "發(fā)送到塊設(shè)備:", io_bo
  print "每秒的中斷數(shù):", system_interrupt
  print "每秒的上下文切換數(shù):", system_context_switch
  print "用戶空間上進(jìn)程運(yùn)行的時(shí)間百分比:", cpu_user
  print "內(nèi)核空間上進(jìn)程運(yùn)行的時(shí)間百分比:", cpu_sys
  print "閑置時(shí)間百分比:", cpu_idle
  print "等待IO的時(shí)間百分比:", cpu_wait
  print "從虛擬機(jī)偷取的時(shí)間百分比:", st
 
 
'''
cpu監(jiān)控
'''
def cpu_info():
  child = ssh_command("遠(yuǎn)程服務(wù)器用戶名", "127.0.0.1", "遠(yuǎn)程服務(wù)器密碼", "cat /proc/cpuinfo")
  child.expect(pexpect.EOF)
  cpuinfo = child.before
  cpu_num = re.findall('processor.*?(\d+)', cpuinfo)[-1]
  cpu_num = str(int(cpu_num) + 1)
  print '***************************************cpu監(jiān)控***************************************'
  print "*******************時(shí)間:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "******************"
  print u"CPU數(shù)目:", cpu_num
  li = cpuinfo.replace('\t', '').split('\r')
  CPUinfo = {}
  procinfo = {}
  nprocs = 0
  for line in li:
    if line.find("processor") > -1:
      CPUinfo['CPU%s' % nprocs] = procinfo
      nprocs = nprocs + 1
    else:
      if len(line.split(':')) == 2:
        procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()
      else:
        procinfo[line.split(':')[0].strip()] = ''
  for processor in CPUinfo.keys():
    print "CPU屬于的名字及其編號(hào)、標(biāo)稱(chēng)主頻:",CPUinfo[processor]['model name']
    print "CPU屬于其系列中的哪一代的代號(hào):", CPUinfo[processor]['model']
    print "CPU制造商:", CPUinfo[processor]['vendor_id']
    print "CPU產(chǎn)品系列代號(hào):", CPUinfo[processor]['cpu family']
    print "CPU的實(shí)際使用主頻:", CPUinfo[processor]['cpu MHz']
 
 
"""
負(fù)載均衡
"""
def load_stat():
  child = ssh_command("遠(yuǎn)程服務(wù)器用戶名", "127.0.0.1", "遠(yuǎn)程服務(wù)器密碼", "cat /proc/loadavg")
  child.expect(pexpect.EOF)
  loadavgs = child.before.strip().split()
  print '************************負(fù)載均衡監(jiān)控****************************'
  print "*******************時(shí)間:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),"******************"
  print "系統(tǒng)5分鐘前的平均負(fù)載:", loadavgs[0]
  print "系統(tǒng)10分鐘前的平均負(fù)載:", loadavgs[1]
  print "系統(tǒng)15分鐘前的平均負(fù)載:", loadavgs[2]
  print "分子是正在運(yùn)行的進(jìn)程數(shù),分母為總進(jìn)程數(shù):",loadavgs[3]
  print "最近運(yùn)行的進(jìn)程id:", loadavgs[4]
 
 
 
"""
獲取網(wǎng)絡(luò)接口的輸入和輸出
"""
def ionetwork():
  child = ssh_command("遠(yuǎn)程服務(wù)器用戶名", "127.0.0.1", "遠(yuǎn)程服務(wù)器密碼", "cat /proc/net/dev")
  child.expect(pexpect.EOF)
  netdata = child.before
  li = netdata.strip().split('\n')
  print '************************獲取網(wǎng)絡(luò)接口的輸入和輸出監(jiān)控****************************'
  print "*******************時(shí)間:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),"******************"
  net = {}
  for line in li[2:]:
    line = line.split(":")
    eth_name = line[0].strip()
    # if eth_name != 'lo':
    net_io = {}
    net_io['Receive'] = round(float(line[1].split()[0]) / (1024.0 * 1024.0), 2)
    net_io['Transmit'] = round(float(line[1].split()[8]) / (1024.0 * 1024.0), 2)
    net[eth_name] = net_io
  print net
 
 
""" 
磁盤(pán)空間監(jiān)控
"""
def disk_stat():
  child = ssh_command("遠(yuǎn)程服務(wù)器用戶名", "127.0.0.1", "遠(yuǎn)程服務(wù)器密碼", "df -h")
  child.expect(pexpect.EOF)
  disk = child.before
  disklist = disk.strip().split('\n')
  disklists=[]
  for disk in disklist:
    disklists.append(disk.strip().split())
  print '************************磁盤(pán)空間監(jiān)控****************************'
  print "*******************時(shí)間:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "******************"
  for i in disklists[1:]:
    print "\t文件系統(tǒng):", i[0],
    print "\t容量:", i[1],
    print "\t已用:", i[2],
    print "\t可用:", i[3],
    print "\t已用%掛載點(diǎn):", i[4]
 
 
""" 
端口監(jiān)控
一般是遠(yuǎn)程服務(wù)器用戶名用戶
"""
def getComStr():
  child = ssh_command("遠(yuǎn)程服務(wù)器用戶名", "127.0.0.1", "遠(yuǎn)程服務(wù)器密碼", "netstat -tpln")
  child.expect(pexpect.EOF)
  Com = child.before
  print '******************************端口監(jiān)控*********************************'
  print "*******************時(shí)間:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "******************"
  print Com
 
 
 
"""
獲取網(wǎng)絡(luò)接口的輸入和輸出
"""
def cpu():
  child = ssh_command("遠(yuǎn)程服務(wù)器用戶名", "127.0.0.1", "遠(yuǎn)程服務(wù)器密碼", 'cat /proc/stat | grep "cpu "')
  child.expect(pexpect.EOF)
  child1 = ssh_command("遠(yuǎn)程服務(wù)器用戶名", "127.0.0.1", "遠(yuǎn)程服務(wù)器密碼", 'cat /proc/stat | grep "cpu "')
  child1.expect(pexpect.EOF)
  cpus = child.before.strip().split()
  cpus1 = child1.before.strip().split()
  print '************************cpu使用情況****************************'
  print "*******************時(shí)間:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),"******************"
  T1=int(cpus[1])+int(cpus[2])+int(cpus[3])+int(cpus[4])+int(cpus[5])+int(cpus[6])+int(cpus[8])+int(cpus[9])
  T2=int(cpus1[1]) + int(cpus1[2]) + int(cpus1[3]) + int(cpus1[4] )+ int(cpus1[5] )+int( cpus1[6] )+ int(cpus1[8] )+ int(cpus1[9])
  Tol=T2-T1
  Idle=int(cpus1[4]) - int(cpus[4])
  print '總的cpu時(shí)間1:',T1
  print '總的cpu時(shí)間2:', T2
  print '時(shí)間間隔內(nèi)的所有時(shí)間片:', Tol
  print '計(jì)算空閑時(shí)間idle:', Idle
  print "計(jì)算cpu使用率:",100*(Tol-Idle)/Tol,"%"
 
"""
第一種執(zhí)行
"""
def alltask():
  try:
    threads = []
    t1 = threading.Thread(target=mem_info)
    threads.append(t1)
    t2 = threading.Thread(target=vm_stat_info)
    threads.append(t2)
    t3 = threading.Thread(target=cpu_info)
    threads.append(t3)
    t4 = threading.Thread(target=load_stat)
    threads.append(t4)
    t5 = threading.Thread(target=ionetwork)
    threads.append(t5)
    t6 = threading.Thread(target=disk_stat)
    threads.append(t6)
    t7 = threading.Thread(target=getComStr)
    threads.append(t7)
    t8 = threading.Thread(target=cpu)
    threads.append(t8)
    for n in range(len(threads)):
      threads[n].start()
  except Exception, e:
    print str(e)
 
"""
第二種執(zhí)行
"""
if __name__ == '__main__':
  try:
    threads = []
    t1 = threading.Thread(target=mem_info)
    threads.append(t1)
    t2 = threading.Thread(target=vm_stat_info)
    threads.append(t2)
    t3 = threading.Thread(target=cpu_info)
    threads.append(t3)
    t4 = threading.Thread(target=load_stat)
    threads.append(t4)
    t5 = threading.Thread(target=ionetwork)
    threads.append(t5)
    t6 = threading.Thread(target=disk_stat)
    threads.append(t6)
    t7 = threading.Thread(target=getComStr)
    threads.append(t7)
    t8 = threading.Thread(target=cpu)
    threads.append(t8)
    for n in range(len(threads)):
      threads[n].start()
  except Exception, e:
    print str(e)

監(jiān)控結(jié)果如下:

接下來(lái)做的是把監(jiān)控結(jié)果可視化,即可,可惜沒(méi)時(shí)間做,就交給各位了?。?!

花了兩天時(shí)間整理的,分享給大家,希望對(duì)各位有幫助!?。?/p>

以上所述是小編給大家介紹的用Python實(shí)現(xiàn)自動(dòng)化監(jiān)控遠(yuǎn)程服務(wù)器詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • PyTorch?之?強(qiáng)大的?hub?模塊和搭建神經(jīng)網(wǎng)絡(luò)進(jìn)行氣溫預(yù)測(cè)

    PyTorch?之?強(qiáng)大的?hub?模塊和搭建神經(jīng)網(wǎng)絡(luò)進(jìn)行氣溫預(yù)測(cè)

    hub 模塊是調(diào)用別人訓(xùn)練好的網(wǎng)絡(luò)架構(gòu)以及訓(xùn)練好的權(quán)重參數(shù),使得自己的一行代碼就可以解決問(wèn)題,方便大家進(jìn)行調(diào)用,這篇文章主要介紹了PyTorch?之?強(qiáng)大的?hub?模塊和搭建神經(jīng)網(wǎng)絡(luò)進(jìn)行氣溫預(yù)測(cè),需要的朋友可以參考下
    2023-03-03
  • python判斷圖片寬度和高度后刪除圖片的方法

    python判斷圖片寬度和高度后刪除圖片的方法

    這篇文章主要介紹了python判斷圖片寬度和高度后刪除圖片的方法,涉及Python中os模塊與Image模塊的相關(guān)使用技巧,需要的朋友可以參考下
    2015-05-05
  • Python使用PyMuPDF實(shí)現(xiàn)添加PDF水印

    Python使用PyMuPDF實(shí)現(xiàn)添加PDF水印

    在日常工作中,我們經(jīng)常需要對(duì)PDF文件進(jìn)行處理,其中一項(xiàng)常見(jiàn)的需求是向PDF文件添加水印,本文將介紹如何使用Python編程語(yǔ)言和PyMuPDF庫(kù)在PDF文件中添加水印,感興趣的可以了解一下
    2023-08-08
  • 一個(gè)可以套路別人的python小程序?qū)嵗a

    一個(gè)可以套路別人的python小程序?qū)嵗a

    本文通過(guò)一段實(shí)例代碼給大家分享一個(gè)可以套路別人的python小程序,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-04-04
  • Flask 入門(mén)Web 微框架Hello Flask

    Flask 入門(mén)Web 微框架Hello Flask

    這篇文章主要介紹了 Flask 入門(mén)Web 微框架Hello Flask,F(xiàn)lask 是一個(gè) Python 實(shí)現(xiàn)的 Web 微框架,之所以稱(chēng)之為微框架,是因?yàn)?nbsp;Flask 核心簡(jiǎn)單且易于擴(kuò)展,有兩個(gè)主要依賴(lài),WSGI工具集:Werkzeug和模板引擎:Jinja2,Flask 只保留了 Web 開(kāi)發(fā)的核心功能,需要的朋友可以參考一下
    2021-11-11
  • Python安裝spark的詳細(xì)過(guò)程

    Python安裝spark的詳細(xì)過(guò)程

    這篇文章主要介紹了Python安裝spark的詳細(xì)過(guò)程,本文通過(guò)圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-10-10
  • 教你用Python來(lái)制作一個(gè)自動(dòng)搶票的腳本小程序

    教你用Python來(lái)制作一個(gè)自動(dòng)搶票的腳本小程序

    大麥網(wǎng),是中國(guó)綜合類(lèi)現(xiàn)場(chǎng)娛樂(lè)票務(wù)營(yíng)銷(xiāo)平臺(tái),業(yè)務(wù)覆蓋演唱會(huì)、 話劇、音樂(lè)劇、體育賽事等領(lǐng)域,但是因?yàn)槠睌?shù)有限,還有黃牛們不能丟了飯碗,所以導(dǎo)致了,很多人都搶不到票,那么,今天帶大家用Python來(lái)制作一個(gè)自動(dòng)搶票的腳本小程序,需要的朋友可以參考下
    2023-07-07
  • python之singledispatch單分派問(wèn)題

    python之singledispatch單分派問(wèn)題

    這篇文章主要介紹了python之singledispatch單分派問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Python Tricks 使用 pywinrm 遠(yuǎn)程控制 Windows 主機(jī)的方法

    Python Tricks 使用 pywinrm 遠(yuǎn)程控制 Windows 主機(jī)的方法

    這篇文章主要介紹了Python Tricks 使用 pywinrm 遠(yuǎn)程控制 Windows 主機(jī)的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-07-07
  • Python 3.8中實(shí)現(xiàn)functools.cached_property功能

    Python 3.8中實(shí)現(xiàn)functools.cached_property功能

    這篇文章主要介紹了Python 3.8中實(shí)現(xiàn)functools.cached_property功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-05-05

最新評(píng)論

枞阳县| 阳江市| 凤冈县| 交口县| 深水埗区| 循化| 彩票| 安徽省| 同江市| 宁夏| 石门县| 温泉县| 奇台县| 元氏县| 庐江县| 红桥区| 金山区| 永城市| 桑植县| 象山县| 襄垣县| 张家口市| 宝鸡市| 三河市| 清河县| 凉山| 湘潭县| 阳泉市| 友谊县| 香港 | 延寿县| 宿迁市| 井研县| 潜江市| 思南县| 鹤峰县| 阿鲁科尔沁旗| 南昌市| 高台县| 宁乡县| 沁阳市|