Python获取CPU使用率、内存使用率、网络使用状态

2015年7月10日 11:23 by wst

python运维

参考文章:http://blog.csdn.net/bubu8633/article/details/8258342

由于psutil已更新到3.0.1版本,最新的代码如下:

适用于python2和python3

#!/usr/bin/env python

import os
import time
import sys
import atexit
import psutil

#print "Welcome,current system is",os.name," 3 seconds late start to get data"
time.sleep(3)

line_num = 1

#function of Get cpu state
def getCPUstate(interval=1):
    return (" CPU:"+str(psutil.cpu_percent(interval))+"%")

def getMemorystate():
    phymem = psutil.virtual_memory()
    line = "Memory: %5s%% %6s/%s"%(
            phymem.percent,
            str(int(phymem.used/1024/1024))+"M",
            str(int(phymem.total/1024/1024))+"M"
            )
    return line
def bytes2human(n):
    """
    >>>bytes2human(10000)
    '9.8k'
    >>>bytes2human(100001221)
    '95.4M'
    """
    symbols = ('K','M','G','T','P','E','Z','Y')
    prefix = {}
    for i ,s in enumerate(symbols):
        prefix[s] = 1 << (i+1)*10
    for s in reversed(symbols):
        if n >=prefix[s]:
            value = float(n) / prefix[s]
            return '%.2f %s'%(value,s)
    return '%.2fB'%(n)
def poll(interval):
    """Retrieve raw stats within an interval window."""
    tot_before = psutil.net_io_counters()
    pnic_before = psutil.net_io_counters(pernic=True)
    #sleep some time
    time.sleep(interval)
    tot_after = psutil.net_io_counters()
    pnic_after = psutil.net_io_counters(pernic=True)
    #get cpu stats
    cpu_state = getCPUstate(interval)
    #get memory
    memory_state = getMemorystate()
    return (tot_before,tot_after,pnic_before,pnic_after,cpu_state,memory_state)
def refresh_window(tot_before,tot_after,pnic_before,pnic_after,cpu_state,memory_state):
    """print stats on screen"""
    #print current time,cpu state,memory
    print (time.asctime() +" | "+cpu_state+" | "+
            memory_state)
    #total
    print(" NetStates:")
    print(" total bytes:  sent: %-10s received: %s"%(\
        bytes2human(tot_after.bytes_sent), \
        bytes2human(tot_after.bytes_recv)))
    print( " total packets:  sent: %-10s received: %s"%(\
        tot_after.packets_sent,\
        tot_after.packets_recv))
    # per-network interface details: let's sort network interfaces so    
    # that the ones which generated more traffic are shown first
    print( " ")
    nic_names = pnic_after.keys()
    #nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)
    for name in nic_names:
        stats_before = pnic_before[name]
        stats_after = pnic_after[name]
        templ = "%-15s %15s %15s"    
        print(templ % (name, "TOTAL", "PER-SEC"))  
        print(templ % (
            "bytes-sent",    
            bytes2human(stats_after.bytes_sent),  
            bytes2human(stats_after.bytes_sent - stats_before.bytes_sent) +
            '/s', 
            ))
        print(templ % (    
            "bytes-recv",    
            bytes2human(stats_after.bytes_recv),    
            bytes2human(stats_after.bytes_recv- stats_before.bytes_recv)
            + '/s',    
            ))
        print(templ % ( 
            "pkts-sent",
            stats_after.packets_sent,
            stats_after.packets_sent - stats_before.packets_sent,
            ))
        print((templ %(
            "pkts-recv", 
            stats_after.packets_recv,
            stats_after.packets_recv - stats_before.packets_recv,
            )))
        print( " ")
try:
    interval = 0
    while 1:
        args = poll(interval)
        refresh_window(*args)
        interval = 1
except (KeyboardInterrupt,SystemExit):
    pass

如需获取个别进程的状态,请关注后续文章

如有疑问请在下方评论,或加我微信:wst_ccut


Comments(128) Add Your Comment

Charlesnag
“I haven’t seen you in these parts,” the barkeep said, sidling over to where I sat. “Personage’s Bao.” He stated it exuberantly, as if word of his exploits were shared by means of settlers around multitudinous a fire in Aeternum. He waved to a wooden tun hard by us, and I returned his gesture with a nod. He filled a telescope and slid it to me across the stained red wood of the excluding before continuing. “As a betting fellow, I’d be willing to wager a fair speck of coin you’re in Ebonscale Reach for more than the swig and sights,” he said, eyes glancing from the sword sheathed on my hip to the bow slung across my back. http://www.google.vg/url?q=https://renewworld.ru/sistemnye-trebovaniya-new-world/
Hwebmk
lipitor 10mg generic <a href="https://lipiws.top/">buy lipitor 20mg online</a> buy atorvastatin 80mg generic
Icejpr
ciprofloxacin 500mg cheap - <a href="https://metroagyl.top/clindamycin/">buy sulfamethoxazole online</a> amoxiclav tablet
Fdyztq
buy cipro medication - <a href="https://cipropro.top/gemyambutol/">buy myambutol paypal</a> purchase amoxiclav pills
Ankxtn
buy metronidazole 400mg for sale - <a href="https://metroagyl.top/oxytetracycline/">order generic terramycin</a> order azithromycin sale
Hpgcmk
purchase ciplox for sale - <a href="https://septrim.top/doryx/">buy doryx tablets</a> erythromycin 250mg cheap
Jttvcp
order valtrex 1000mg pill - <a href="https://gnantiviralp.com/zovirax/">order acyclovir 400mg for sale</a> order acyclovir 800mg sale
Kozisi
ivermectin 6mg pills for humans - <a href="https://keflexin.top/aczone/">order aczone online</a> buy tetracycline 250mg for sale
Qbydwz
metronidazole 200mg oral - <a href="https://metroagyl.top/azithromycin/">order azithromycin 250mg generic</a> order zithromax 500mg
Fozqgs
purchase ampicillin <a href="https://ampiacil.top/doxycyclineantb/">acticlate for sale</a> how to buy amoxicillin
Ehwjra
order furosemide for sale - <a href="https://antipathogenc.com/">lasix usa</a> buy captopril 25mg without prescription
Cfafsm
buy glycomet 500mg pill - <a href="https://gnantiacidity.com/duricef/">buy cefadroxil 250mg pill</a> buy lincomycin 500 mg online cheap
Rqwrlq
retrovir 300 mg generic - <a href="https://canadiangnp.com/rulide/">buy roxithromycin pills</a> buy allopurinol 100mg pill
Atbbrr
clozaril 100mg for sale - <a href="https://genonlinep.com/pepcid/">order pepcid 40mg pill</a> famotidine brand
Mlmfem
seroquel 100mg usa - <a href="https://gnkantdepres.com/geodon/">order geodon 40mg for sale</a> order eskalith generic
Ysbqar
anafranil over the counter - <a href="https://antdeponline.com/celexa/">celexa 20mg price</a> order doxepin pills
Pvopfh
buy atarax pills - <a href="https://antdepls.com/">atarax 25mg usa</a> order endep 10mg online
Rmaqmj
cheap amoxil for sale - <a href="https://atbioxotc.com/erythromycin/">erythromycin 500mg oral</a> order ciprofloxacin 1000mg pill
Xhcfmc
amoxiclav cheap - <a href="https://atbioinfo.com/">buy clavulanate without prescription</a> purchase ciprofloxacin generic
Vzhefj
clindamycin canada - <a href="https://cadbiot.com/cefixime/">order generic cefixime</a> chloromycetin usa
Htfzke
buy generic azithromycin over the counter - <a href="https://gncatbp.com/emetronidazole/">buy metronidazole medication</a> buy ciprofloxacin 500 mg pills
Vsmbpe
where to buy stromectol online - <a href="https://antibpl.com/">ivermectin 6mg for humans for sale</a> cefaclor 500mg brand
Qohqyt
buy ventolin inhalator generic - <a href="https://antxallergic.com/cvallegra/">allegra 120mg sale</a> purchase theo-24 Cr for sale
Sfqsmo
clarinex 5mg us - <a href="https://rxtallerg.com/ventolinpill/">ventolin 4mg cost</a> ventolin inhalator brand
Rkljmj
buy methylprednisolone 8mg - <a href="https://ntallegpl.com/getazelastine/">order astelin 10ml generic</a> buy azelastine 10ml for sale
Usgpkx
glyburide 5mg generic - <a href="https://prodeprpl.com/pioglitazone30/">buy pioglitazone 15mg generic</a> forxiga usa
Plqyeb
repaglinide 1mg tablet - <a href="https://depressinfo.com/">repaglinide price</a> empagliflozin pills
Mzzzkl
order glycomet 1000mg without prescription - <a href="https://arxdepress.com/">buy glycomet 1000mg without prescription</a> order acarbose
Nuqkqh
lamisil pill - <a href="https://treatfungusx.com/">terbinafine 250mg for sale</a> buy grifulvin v online
Dnfcnz
buy semaglutide sale - <a href="https://infodeppl.com/ddavpspray/">purchase DDAVP generic</a> cheap DDAVP
Jtjrvh
ketoconazole medication - <a href="https://antifungusrp.com/">buy nizoral medication</a> buy sporanox generic
Gelqsj
buy famciclovir 500mg without prescription - <a href="https://amvinherpes.com/">famvir canada</a> buy valaciclovir 1000mg generic
Lgfbod
buy generic lanoxin - <a href="https://blpressureok.com/">brand lanoxin</a> furosemide 100mg ca
Pzkpwy
order microzide 25 mg for sale - <a href="https://norvapril.com/lisinopril/">zestril 2.5mg uk</a> purchase bisoprolol generic
Cznzpb
order lopressor 50mg pills - <a href="https://bloodpresspl.com/">lopressor 50mg pill</a> nifedipine 10mg canada
Edjcvs
nitroglycerin online buy - <a href="https://nitroproxl.com/catapres/">clonidine 0.1mg drug</a> diovan 160mg cost
Ounpdc
crestor pills village - <a href="https://antcholesterol.com/ezetimibe/">ezetimibe grandfather</a> caduet buy fudge
Wcwjck
zocor death - <a href="https://canescholest.com/gemfibrozil/">lopid person</a> lipitor rock
Zggqmn
viagra professional online george - <a href="https://edsildps.com/malegra/">malegra want</a> levitra oral jelly bitter
Hhbjsh
dapoxetine either - <a href="https://promedprili.com/levitrawithdapoxetine/">levitra with dapoxetine mad</a> cialis with dapoxetine who
Drshwe
cenforce single - <a href="https://xcenforcem.com/tadalissxtadalafil/">tadalis pills bore</a> brand viagra online dread
Jvxngq
brand cialis bearer - <a href="https://probrandtad.com/brandlevitra/">brand levitra forth</a> penisole busy
Gunydk
cialis soft tabs double - <a href="https://supervalip.com/cialissuperactive/">cialis super active pills labour</a>1 viagra oral jelly dungeon
Tpgusc
brand cialis trouser - <a href="https://probrandtad.com/forzestpills/">forzest recollect</a> penisole citizen
Yqteis
cialis soft tabs online speak - <a href="https://supervalip.com/viagraoraljelly/">viagra oral jelly online sympathy</a> viagra oral jelly island
Hulvya
cenforce wade - <a href="https://xcenforcem.com/cialistadalafil/">tadalafil cialis</a> brand viagra online someone
Ksqaev
dapoxetine hurry - <a href="https://promedprili.com/sildigra/">sildigra fire</a> cialis with dapoxetine gear
Ltippt
acne treatment young - <a href="https://placnemedx.com/">acne medication stiff</a> acne treatment fur
Rtrwhr
asthma medication glove - <a href="https://bsasthmaps.com/">asthma treatment pale</a> asthma medication journal
Tovcym
treatment for uti blush - <a href="https://amenahealthp.com/">uti medication unable</a> uti treatment ocean
Ihzjwk
prostatitis pills week - <a href="https://xprosttreat.com/">prostatitis medications edward</a> prostatitis medications middle
Lkyacz
valtrex pills heart - <a href="https://gnantiviralp.com/">valtrex bridge</a> valtrex full
Wvrkde
claritin stumble - <a href="https://clatadine.top/">claritin grow</a> loratadine medication swift
Qpvpug
claritin pills mile - <a href="https://clatadine.top/">loratadine bound</a> loratadine medication incident
Rstler
priligy seek - <a href="https://prilixgn.top/">dapoxetine seem</a> priligy herself
Haxvnm
promethazine nightmare - <a href="https://prohnrg.com/">promethazine till</a> promethazine rude
Fjygte
ascorbic acid knowledge - <a href="https://ascxacid.com/">ascorbic acid silver</a> ascorbic acid absorb
Fcozry
biaxin hopeful - <a href="https://gastropls.com/albendazole400/">albendazole fly</a> cytotec pills occur
Lgmyjb
florinef level - <a href="https://gastroplusp.com/nexesomeprazole/">esomeprazole lawn</a> prevacid pills important
Atjomp
bisacodyl 5 mg brand - <a href="https://gastroinfop.com/liv52/">buy liv52 paypal</a> liv52 over the counter
Wswasg
rabeprazole 20mg us - <a href="https://gastrointesl.com/metoclopramide/">purchase metoclopramide pill</a> buy motilium no prescription
Hourbf
bactrim 960mg us - <a href="https://tobmycin.com/">order generic tobramycin 10mg</a> buy tobrex cheap
Prmxhe
buy zovirax generic - <a href="https://danaterone.shop/">oral hydroquinone</a> buy duphaston 10 mg online cheap
Lefvom
how to get dapagliflozin without a prescription - <a href="https://sineqpin.com/">sinequan 75mg over the counter</a> purchase acarbose generic
Vwycwz
fulvicin 250 mg ca - <a href="https://dipyrilx.com/">order dipyridamole without prescription</a> gemfibrozil 300 mg canada
Esevve
order vasotec online - <a href="https://xalanoprost.com/">buy xalatan generic</a> cheap latanoprost
Wyduug
buy generic dramamine over the counter - <a href="https://bisacolax.com/">order dramamine 50 mg pills</a> order risedronate 35mg online
Rynvdm
order etodolac - <a href="https://cilosetal.com/">order cilostazol sale</a> buy cilostazol 100mg
Rgnzqe
generic piroxicam 20mg - <a href="https://feldexicam.com/">buy piroxicam generic</a> exelon where to buy
Izoonm
generic nootropil 800mg - <a href="https://nootquin.com/praziquantel/">biltricide pill</a> sinemet 20mg drug
Bqjqld
cost hydroxyurea - <a href="https://hydroydrinfo.com/">hydrea pills</a> buy robaxin 500mg for sale
Nkzjym
buy depakote 500mg sale - <a href="https://adepamox.com/">divalproex generic</a> brand topamax
Ihwnyj
cheap disopyramide phosphate without prescription - <a href="https://anorpica.com/chlorpromazine/">buy chlorpromazine generic</a> buy thorazine 50 mg without prescription
Rxqzjf
order aldactone 25mg without prescription - <a href="https://aldantinep.com/naltrexone/">revia 50 mg canada</a> revia 50mg sale
Gnqkiu
flexeril 15mg uk - <a href="https://abflequine.com/primaquine/">buy primaquine pills for sale</a> enalapril buy online
Nqfzzq
ondansetron where to buy - <a href="https://azofarininfo.com/procyclidine/">buy procyclidine pill</a> ropinirole oral
Kseowz
generic ascorbic acid 500 mg - <a href="https://mdacidinfo.com/lopinavirritonavir/">buy lopinavir ritonavir generic</a> buy generic compro for sale
Mafakk
buy durex gel online - <a href="https://xalaplinfo.com/latanoprosteyedrops/">order zovirax</a> order xalatan online cheap
Umzacx
minoxidil price - <a href="https://hairlossmedinfo.com/finasteridepros/">cheap proscar generic</a> order finasteride 1mg generic
Httcoq
leflunomide 20mg without prescription - <a href="https://infohealthybones.com/alfacalcidol/">buy alfacip tablets</a> order generic cartidin
Uafgsn
purchase atenolol for sale - <a href="https://heartmedinfox.com/">order atenolol 50mg without prescription</a> coreg brand
Toehqp
buy verapamil sale - <a href="https://infoheartdisea.com/cardizem/">buy generic diltiazem 180mg</a> cheap generic tenoretic
Glekac
buy atorvastatin no prescription - <a href="https://infoxheartmed.com/">buy atorlip sale</a> nebivolol 5mg uk
Rimnhg
buy lasuna cheap - <a href="https://infoherbalmz.com/diarex/">purchase diarex pills</a> cost himcolin
Jrgcmp
buy gasex online cheap - <a href="https://herbalinfomez.com/diabecon/">buy generic diabecon over the counter</a> buy diabecon pills
Gghqva
order generic norfloxacin - <a href="https://gmenshth.com/">order norfloxacin</a> oral confido
Pxroww
buy generic speman - <a href="https://spmensht.com/himplasia/">order himplasia for sale</a> fincar cost
Uszawp
buy finax no prescription - <a href="https://finmenura.com/alfuzosin/">order alfuzosin 10 mg for sale</a> uroxatral 10mg cost
Icpyzu
terazosin over the counter - <a href="https://hymenmax.com/dapoxetine/">priligy online buy</a> cost priligy 60mg
Wkmgbn
oxcarbazepine 300mg for sale - <a href="https://trileoxine.com/pirfenidone/">pirfenidone over the counter</a> levothyroxine pills
Xordcl
buy lactulose bottles for sale - <a href="https://duphalinfo.com/betahistine/">betahistine 16mg cheap</a> order betahistine without prescription
Otpqxu
order imusporin without prescription - <a href="https://asimusxate.com/gloperba/">order colchicine pills</a> generic gloperba
Fuvkpf
calcort for sale online - <a href="https://lazacort.com/brimonidine/">order brimonidine generic</a> buy generic alphagan
Nhuchu
purchase besifloxacin without prescription - <a href="https://besifxcist.com/sildamax/">buy sildamax paypal</a> sildamax sale
Sumzvz
brand probenecid 500mg - <a href="https://bendoltol.com/monograph/">monograph oral</a> tegretol cost
Rbjhpg
gabapentin 600mg tablet - <a href="https://aneutrin.com/">buy gabapentin 800mg pill</a> order azulfidine
Hcoflv
colospa online - <a href="https://coloxia.com/etoricoxib/">purchase etoricoxib generic</a> order generic pletal 100mg
Kqxhwp
celecoxib oral - <a href="https://celespas.com/">order celebrex online cheap</a> order indomethacin pills
Zzuvfa
rumalaya online - <a href="https://rumaxtol.com/shallaki/">buy shallaki pills for sale</a> buy amitriptyline medication
Wmphux
buy diclofenac 50mg sale - <a href="https://dicloltarin.com/aspirin/">purchase aspirin pill</a> how to buy aspirin
Qusmox
buy generic voveran - <a href="https://vovetosa.com/">diclofenac usa</a> buy nimodipine generic
Myvlwd
buy pyridostigmine - <a href="https://mestonsx.com/">buy mestinon 60mg</a> buy generic imuran
Cdgbpi
meloxicam 7.5mg uk - <a href="https://meloxiptan.com/rtrizatriptan/">ketorolac generic</a> buy ketorolac cheap
Uadvso
order generic baclofen 25mg - <a href="https://baclion.com/">ozobax online buy</a> purchase piroxicam without prescription
Vcjdjb
purchase trihexyphenidyl sale - <a href="https://voltapll.com/diclofenacgel/">purchase emulgel for sale</a> buy emulgel
Recdvf
cyproheptadine order online - <a href="https://periheptadn.com/">periactin 4mg uk</a> cheap zanaflex
Oeuvud
purchase isotretinoin - <a href="https://aisotane.com/asavlosulfon/">dapsone 100mg tablet</a> buy deltasone 5mg generic
Nnmrox
order generic omnicef 300mg - <a href="https://omnixcin.com/aminocycline/"></a> buy clindamycin online
Wxqclw
permethrin online - <a href="https://actizacs.com/tretinoin/">tretinoin price</a> oral retin
Wploro
order deltasone 10mg generic - <a href="https://apreplson.com/">prednisone usa</a> buy permethrin cream
Fdegnw
metronidazole 400mg pill - <a href="https://ametronles.com/">order generic flagyl</a> cenforce pill
Cvvpwv
betnovate cost - <a href="https://betnoson.com/">betnovate 20 gm for sale</a> order monobenzone online
Yljfxz
cleocin cost - <a href="https://indometnp.com/">order indocin</a> indocin 75mg capsule
Cfsbfy
cost augmentin 1000mg - <a href="https://baugipro.com/">buy cheap augmentin</a> purchase levothyroxine without prescription
Gawmin
buy eurax paypal - <a href="https://aeuracream.com/abactroban/">order mupirocin generic</a> generic aczone
Lylmap
purchase hyzaar generic - <a href="https://acephacrsa.com/">order keflex 250mg pills</a> order keflex generic
Khbqqp
zyban order online - <a href="https://bupropsl.com/orlistat/">order generic orlistat 120mg</a> buy shuddha guggulu generic
Ohelbs
order modafinil sale - <a href="https://sleepagil.com/phenergan/">buy promethazine without prescription</a> how to buy melatonin
Acxvtp
progesterone tablet - <a href="https://apromid.com/">prometrium 200mg usa</a> purchase clomiphene
Xzhkck
order generic xeloda 500 mg - <a href="https://xelocap.com/danocrine/">buy danocrine 100mg generic</a> buy danazol 100 mg pills
Oetori
order aygestin sale - <a href="https://norethgep.com/">aygestin 5mg sale</a> yasmin pills
Pkpmbd
fosamax 70mg sale - <a href="https://pilaxmax.com/medroxyprogesterone/">buy medroxyprogesterone 5mg without prescription</a> provera order online
Umkkoc
order dostinex 0.5mg pills - <a href="https://adostilin.com/alesse/">purchase alesse online cheap</a> alesse buy online
Fcsssp
yasmin drug - <a href="https://festrolp.com/anastrozole/">arimidex online buy</a> arimidex medication
Jtjfpr
г‚·гѓ«гѓ‡гѓЉгѓ•г‚Јгѓ« её‚иІ© гЃЉгЃ™гЃ™г‚Ѓ - <a href="https://jpedpharm.com/">г‚їгѓЂгѓ©гѓ•г‚Јгѓ« её‚иІ© гЃЉгЃ™гЃ™г‚Ѓ</a> г‚·г‚ўгѓЄг‚№ жµ·е¤–йЂљиІ©
Tturuv
гѓ—гѓ¬гѓ‰гѓ‹гѓі и–¬е±ЂгЃ§иІ·гЃ€г‚‹ - <a href="https://jpaonlinep.com/jamoxicillin/">г‚ўгѓўг‚­г‚·г‚·гѓЄгѓі жµ·е¤–йЂљиІ©</a> г‚ёг‚№гѓ­гѓћгѓѓг‚Ї гЃ©гЃ“гЃ§иІ·гЃ€г‚‹
Uxysmx
eriacta quick - <a href="https://eriagra.com/">eriacta appeal</a> forzest course
Xmxriq
プレドニン 値段 - <a href="https://jpanfarap.com/">プレドニン の購入</a> アキュテインは薬局で買える?