....................................../////.===Shadow-Here===./////................................................ > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < ------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// RIFF¤ WEBPVP8 ˜ ðÑ *ôô>‘HŸK¥¤"§£±¨àð enü¹%½_F‘åè¿2ºQú³íªú`N¿­3ÿƒügµJžaÿ¯ÿ°~¼ÎùnúîÞÖô•òíôÁÉß®Sm¥Ü/ ‡ó˜f£Ùà<˜„xëJ¢Ù€SO3x<ªÔ©4¿+ç¶A`q@Ì“Úñè™ÍÿJÌ´ª-˜ÆtÊÛL]Ïq*‘Ý”ì#ŸÌÏãY]@ê`¿ /ªfkØB4·®£ó z—Üw¥Pxù–ÞLШKÇN¾AkÙTf½è'‰g gÆv›Øuh~ a˜Z— ïj*á¥t d£“uÒ ¨`K˜¹ßþ]b>˜]_ÏÔ6W—è2r4x•íÖ…"ƒÖNîä!¦å Ú}ýxGøÌ —@ ;ÆÚŠ=ɾ1ý8lªË¥ô ^yf®Œ¢u&2©nÙÇ›ñÂñŒ³ aPo['½»øFùà­+4ê“$!lövlüÞ=;N®3ð‚õ›DÉKòÞ>ÄÍ ¥ˆuߤ#ˆ$6ù™¥îЇy’ÍB¼ çxÛ;X"WL£R÷͝*ó-¶Zu}º.s¸sšXqù–DþÿvªhüïwyŸ ¯é³lÀ:KCûÄ£Ëá\…­ ~—ýóî ¼ûûÜTÓüÇy…ŽÆvc»¾×U ñ¸žþоP÷¦ó:Ò¨¨5;Ð#&#ÖúñläÿÁœ GxÉ­/ñ‡áQðìYÉtÒw޼GÔ´zàÒò ð*ëzƒ•4~H]Ø‹f ñÓÈñ`NåWçs'ÆÏW^ø¹!XžµmQ5ÃËoLœÎ: ÞËÍ¥J ù…î èo£ßPÎñ¶ž8.Œ]ʵ~5›ÙË-ù*8ÙÖß±~ ©¹rÓê‚j¶d¸{^Q'˜±Crß ÚH—#¥¥QlÀ×ëã‡DÜ«èî þ&Çæžî;ŽÏºò6ÒLÃXy&ZŒ'j‚¢Ù€IßÚù+–MGi‰*jE€‘JcÜ ÓÌ EÏÚj]o˜ Þr <¾U ûŪæÍ/šÝH¥˜b”¼ ÁñßX GP›ï2›4WŠÏà×£…íÓk†¦H·ÅíMh–*nó÷à]ÁjCº€b7<ب‹¨5車bp2:Á[UªM„QŒçiNMa#<5›áËó¸HýÊ"…×Éw¹¦ì2º–x<›»a±¸3Weü®FÝ⑱ö–î–³|LPÈ~çð~Çå‡|º kD¢µÏàÆAI %1À% ¹Ò – ”ϝS¦‰4&¶£°à Öý”û_Ò Áw°A«Å€?mÇÛgHÉ/8)á¾ÛìáöŽP í¨PŸNÙµº¦‡§Ùš"ÿ«>+ªÕ`Ê÷‡‚ß Õû˜þãÇ-PÍ.¾XV‘€ dÜ"þ4¹ ±Oú‘©t¥¦FªÄÃÄ•b‚znýu½—#cDs˜ÃiÑOˆñ×QO=*IAÊ,¶ŽZƒ;‡wøXè%EÐk:F±Ú” .Ѽ+Áu&Ç`."pÈÉw o&¿dE6‘’EqTuK@Ì¥ã™À(Êk(h‰,H}RÀIXÛš3µ1©_OqÚÒJAñ$ÊÙÜ;D3çŒ[þùœh¬Ã³™ö6ç†NY".Ú‰ï[ªŸŒ '²Ð öø_¨ÂÉ9ué¶³ÒŠõTàîMØ#û¯gN‡bÙ놚X„ö …ÉeüÌ^J ‹€.œ$Æ)βÄeæW#óüßĺŸ€ ÀzwV 9oä»f4V*uB «Ë†¹ì¯žR霓æHXa=&“I4K;¯ç‹h×·"UŠ~<•╪Vêª&ÍSÃÆÅ?ÔqÎ*mTM ˜›µwêd#[C¡©§‘D<©àb†–ÁœøvH/,í:¯( ²£|4-„Æövv„Yͼ™^Á$ˆ„¢Û[6yB.åH*V¨æ?$=˜Ñ€•ñ·­(VlŸ‘ nÀt8W÷´Bûba?q9ú¶Xƒl«ÿ\ù¶’þòUÐj/õ¢Ìµ³g$ƒÎR!¸»|Oߍë’BhîÚÑ¢ñåŒJ„®„£2Ð3•ô02Nt…!£Í]Ïc½Qÿ?ˆ<&ÃA¾Ú,JˆijÌ#5yz„‰Î|ÊŽ5QÏ:‹ÐaóVÔxW—CpeÏzÐïíçôÿÅ_[hãsÐ_/ŽTÝ?BîˆííV$<¿i>²F¬_Eß¿ †bÊŒº­ÿ®Z H“C}”¬,Mp ý/Bá£w>˜YV°aƒúh+cŠ- r/[%|üUMHäQ°X»|û/@|°¥Ð !BÔ Ç¢Ä©š+Õì D«7ìN¶ŽðÔ " ƶ’ÖçtA‰Û×}{tþz­¾GÍ›k¹OEJR$ Â׃ «ëÁ"oÉôž$oUK(Ä)Ãz³Ê-‹êN[Ò3Œñbï8P 4ƒ×q¢bo|?<ÛX¬òÄͰL–±›(™ûG?ýË©ÚÄ–ÂDØÐ_Ç¡ô ¾–ÄÏø ×e8Ë©$ÄF¹Å‹ì[©óìl:F¾f´‹‹Xì²ï®\¬ôùƒ ÿat¥óèÒùHß0äe‚;ü×h:ÆWðHž=Ã8骣"kœ'Y?³}Tûè€>?0l›e1Lòñ„aæKÆw…hÖŠùW…ÈÆÄ0ši·›[pcwËþñiêíY/~-Á5˜!¿†A›™Mÿþ(±“t@â“ö2­´TG5yé]çå僳 .·ÍïçÝ7UÚ±Ð/Nè»,_Ï ùdj7\ï Wì4›„»c¸àešg#ÒÊ⥭áØo5‘?ÌdÝô¯ ¹kzsƒ=´#ëÉK›Ø´±-¥eW?‡çßtòTã…$Ý+qÿ±ƒ÷_3Ô¥í÷:æ–ž<·Ö‡‰Å¢ š‡%Ô—utÌÈìðžgÖÀz²À—ï÷Óîäõ{K'´È÷³yaÏÁjƒô}ž§®æÊydÕÈë5¯èˆõvÕ©ã*çD„ “z„Ó‡^^xÂ3M§A´JG‚öï 3W'ˆ.OvXè¡ÊÕª?5º7†˜(˜Ç¶#çê’¶!ÌdZK§æ 0fãaN]òY³RV ™î$®K2R¨`W!1Ôó\;Ý ýB%qæK•&ÓÈe9È0êI±žeŸß -ú@žQr¦ ö4»M¼Áè¹µmw 9 EÆE_°2ó„ŸXKWÁ×Hóì^´²GѝF©óäR†¦‰ç"V»eØ<3ùd3ÿÚ¤Žú“Gi" —‘_ÙËÎ~Üö¯¥½Î»üŸEÚŽåmÞþí ;ÞólËΦMzA"Âf(´òá;Éï(/7½ûñÌ­cïÕçлþÝz¾-ÍvÑ“pH­–ðÓj$¸Äû¤‚‘ãUBË-n“2åPkS5&‹Â|+g^œ®Ì͆d!OïäîU«c;{Û!ÅŽ«ëZ9Ókóˆ]¯ƒ›né `ÇÒ+tÆš (ØKá¾—=3œ®•vuMñg²\ï Ec€ 05±d™‡×iÇ×›UúvÌ¢£Èþ¡ÕØô¶ßÎA"ß±#Ö²ˆÊŸ¦*Ä~ij|àø.-¼'»Ú¥£h ofº¦‡VsR=N½„Î v˜Z*SÌ{=jÑB‹tê…;’HžH¯8–îDù8ñ¢|Q•bÛçš–‹m³“ê¨ åÏ^m¬Žãþ©ïêO‡½6] µÆ„Ooòü ²x}N¦Ë3ïé¿»€›HA˜m%çÞ/¿í7Fø“‹léUk)É°Œµ8Q8›:ÀŠeT*šõ~ôڝG6 ¢}`ùH­–”¡k ‰P1>š†®9z11!X wKfmÁ¦xÑ,N1Q”–æB¶M…ÒÃv6SMˆhU¬ÊPŽï‘öj=·CŒ¯u¹ƒVIЃsx4’ömÛýcå¡¶7ßŠß 57^\wÒÐÆ k§h,Œý î«q^R½3]J¸ÇðN ‚çU¬ôº^Áì} ³f©Õœ§ˆã:FÄÈ‚é(€™?àýÓüè1Gô£¼éj‚OÅñ  #>×—ßtà 0G¥Åa뀐kßhc™À_ÉñÞ#±)GD" YîäË-ÿÙ̪ ¹™a¯´¢E\ÝÒö‚;™„ë]_ p8‰o¡ñ+^÷ 3‘'dT4œŽ ðVë½° :¬víÑ«£tßÚS-3¶“þ2 †üüʨòrš¹M{É_¤`Û¨0ìjœøJ‡:÷ÃáZ˜†@GP&œÑDGÏs¡þ¦þDGú‘1Yá9Ôþ¼ ûø…§÷8&–ÜÑnÄ_m®^üÆ`;ÉVÁJ£?â€-ßê}suÍ2sõA NÌúA磸‘îÿÚ»ƒìö·á¿±tÑÐ"Tÿü˜[@/äj¬€uüªìù¥Ý˜á8Ý´sõj 8@rˆð äþZÇD®ÿUÏ2ùôõrBzÆÏÞž>Ì™xœ“ wiÎ×7_… ¸ \#€MɁV¶¥üÕÿPÔ9Z‡ø§É8#H:ƒ5ÀÝå9ÍIŒ5åKÙŠ÷qÄ>1AÈøžj"µÂд/ªnÀ qªã}"iŸBå˜ÓÛŽ¦…&ݧ;G@—³b¯“•"´4í¨ôM¨åñC‹ïùÉó¯ÓsSH2Ý@ßáM‡ˆKÀªÛUeø/4\gnm¥‹ŸŒ qÄ b9ÞwÒNÏ_4Ég³ú=܆‚´ •â¥õeíþkjz>éÚyU«Íӝ݃6"8/ø{=Ô¢»G¥ äUw°W«,ô—¿ãㆅү¢³xŠUû™yŒ (øSópÐ 9\åTâ»—*oG$/×ÍT†Y¿1¤Þ¢_‡ ¼ „±ÍçèSaÓ 3ÛMÁBkxs‰’R/¡¤ˆÙçª(*õ„üXÌ´ƒ E§´¬EF"Ù”R/ÐNyÆÂ^°?™6¡œïJ·±$§?º>ÖüœcNÌù¯G ‹ñ2ЁBB„^·úìaz¨k:#¨Æ¨8LÎõލ£^§S&cŒÐU€ü(‡F±Š¼&P>8ÙÁ ‰ p5?0ÊÆƒZl¸aô š¼¡}gÿ¶zÆC²¹¬ÎÖG*HB¡O<º2#ñŒAƒ–¡B˜´É$¥›É:FÀÔx¾u?XÜÏÓvN©RS{2ʈãk9rmP¼Qq̳ è¼ÐFׄ^¡Öì fE“F4A…!ì/…¦Lƒ… … $%´¾yã@CI¬ á—3PþBÏNÿ<ý°4Ü ËÃ#ØÍ~âW«rEñw‹eùMMHß²`¬Öó½íf³:‹k˜¯÷}Z!ã¿<¥,\#öµÀ¯aÒNÆIé,Ћ–lŽ#Àæ9ÀÒS·I’½-Ïp Äz¤Š Â* ­íÄ9­< h>׍3ZkËU¹§˜ŒŠ±f­’¤º³Q ÏB?‹#µíÃ¥®@(Gs«†vI¥Mµ‹Á©e~2ú³ÁP4ìÕi‚²Ê^ö@-DþÓàlÜOÍ]n"µã:žpsŽ¢:! Aõ.ç~ÓBûH÷JCÌ]õVƒd «ú´QÙEA–¯¯Œ!.ˆˆëQ±ù œ·Ì!Õâ )ùL„ÅÀlÚè5@B…o´Æ¸XÓ&Û…O«˜”_#‡ƒ„ûÈt!¤ÁÏ›ÎÝŠ?c9 â\>lÓÁVÄÑ™£eØY]:fÝ–—ù+p{™ðè û³”g±OƒÚSù£áÁÊ„ä,ï7š²G ÕÌBk)~ÑiCµ|h#u¤¶îK¨² #²vݯGãeÖ϶ú…¾múÀ¶þÔñ‚Š9'^($¤§ò “š½{éúp÷J›ušS¹áªCÂubÃH9™D™/ZöØÁ‡¦ÝÙŸ·kð*_”.C‹{áXó€‡c¡c€§/šò/&éš÷,àéJþ‰X›fµ“C¨œ®r¬"kL‰Â_q…Z–.ÉL~O µ›zn‚¹À¦Öª7\àHµšÖ %»ÇníV[¥*Õ;ƒ#½¾HK-ÖIÊdÏEÚ#=o÷Óò³´Š: Ç?{¾+9›–‘OEáU·S€˜j"ÄaÜ ŒÛWt› á–c#a»pÔZÞdŽtWê=9éöÊ¢µ~ ë ;Öe‡Œ®:bî3±ýê¢wà¼îpêñ¹¾4 zc¾ðÖÿzdêŒÑÒŝÀ‰s6¤í³ÎÙB¿OZ”+F¤á‡3@Ñëäg©·Ž ˆèª<ù@É{&S„œÕúÀA)‰h:YÀ5^ÂÓŒ°õäU\ ùËÍû#²?Xe¬tu‰^zÒÔãë¼ÛWtEtû …‚g¶Úüâî*moGè¨7%u!]PhÏd™Ý%Îx: VÒ¦ôÊD3ÀŽKÛËãvÆî…N¯ä>Eró–ð`5 Œ%u5XkñÌ*NU%¶áœÊ:Qÿú»“úzyÏ6å-၇¾ ´ ÒÊ]y žO‘w2Äøæ…H’²f±ÎÇ.ª|¥'gîV•Ü .̘¯€šòü¤U~Ù†*¢!?ò wý,}´°ÔÞnïoKq5µb!áÓ3"vAßH¡³¡·G(ÐÎ0Îò¼MG!/ài®@—¬04*`…«é8ªøøló“ˆÊ”èù¤…ßÊoÿé'ËuÌÖ5×È¡§ˆˆfŽë9}hìâ_!!¯  B&Ëö¶‰ÀAÙNVŸ Wh›¸®XÑJì¨ú“¿÷3uj²˜¨ÍÎìë±aúŠÝå¯ð*Ó¨ôJ“yºØ)m°WýOè68†ŸÏ2—‰Ïüꪫٚ¥‹l1 ø ÏÄFjêµvÌbü¦èÝx:X±¢H=MÐß—,ˆÉÇ´(9ú¾^ÅÚ4¿m‡$âX‘å%(AlZo@½¨UOÌÕ”1ø¸jÎÀÃÃ_ µ‘Ü.œº¦Ut: Æï’!=¯uwû#,“pþÇúŒø(é@?³ü¥‘Mo §—s@Œ#)§ŒùkL}NOÆêA›¸~r½¼ÙA—HJ«eˆÖ´*¡ÓpÌŸö.m<-"³ûÈ$¬_6­åf£ïÚâj1y§ÕJ½@dÞÁr&Í\Z%D£Íñ·AZ Û³øüd/ªAi†/Й~  ‡âĮҮÏh§°b—›Û«mJžòG'[ÈYýŒ¦9psl ýÁ ®±f¦x,‰½tN ‚Xª9 ÙÖH.«Lo0×?͹m¡å†Ѽ+›2ƒF ±Ê8 7Hցϓ²Æ–m9…òŸï]Â1äN†VLâCˆU .ÿ‰Ts +ÅÎx(%¦u]6AF Š ØF鈄‘ |¢¶c±soŒ/t[a¾–û:s·`i햍ê›ËchÈ…8ßÀUÜewŒðNOƒõD%q#éû\9¤x¹&UE×G¥ Í—™$ð E6-‡¼!ýpãÔM˜ Âsìe¯ñµK¢Ç¡ùôléœ4Ö£”À Š®Ðc ^¨À}ÙËŸ§›ºê{ÊuÉC ×Sr€¤’fÉ*j!úÓ’Gsùìoîßîn%ò· àc Wp÷$¨˜)û»H ×8ŽÒ€Zj¤3ÀÙºY'Ql¦py{-6íÔCeiØp‘‡XÊîÆUߢ܂ž£Xé¼Y8þ©ëgñß}é.ÎógÒ„ÃØËø¯»™§Xýy M%@NŠ À(~áÐvu7&•,Ù˜ó€uP‡^^®=_E„jt’ 403WebShell
403Webshell
Server IP : 107.180.102.13  /  Your IP : 216.73.216.161
Web Server : Apache
System : Linux ip-107-180-102-13.ip.secureserver.net 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : nobody ( 99)
PHP Version : 7.3.33
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /lib/fm-agent/plugins/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /lib/fm-agent/plugins/bandwidth.py
import agent_util
import sys
import os
from datetime import datetime
from agent_util import float
import fnmatch


class BandwidthPlugin(agent_util.Plugin):
    textkey = "bandwidth"
    label = "Bandwidth"

    @classmethod
    def get_metadata(self, config):
        def add_to_interfaces(iface):
            if any(fnmatch.fnmatch(iface, f) for f in filter_interfaces):
                return
            if type(interfaces) == set:
                interfaces.add(iface)
            else:
                interfaces.append(iface)

        status = agent_util.SUPPORTED
        msg = None
        interfaces = set()
        filter_interfaces = []

        filter_interfaces_config = config.get("filter_interfaces")
        if filter_interfaces_config:
            if filter_interfaces_config[0] == "[":
                filter_interfaces_config = filter_interfaces_config.strip("[]")
            for f in filter_interfaces_config.split(","):
                f = f.strip()
                if f:
                    if f[0] == '"':
                        f = f.strip('"')
                    elif f[0] == "'":
                        f = f.strip("'")
                if f:
                    filter_interfaces.append(f)

        if "freebsd" in sys.platform or "darwin" in sys.platform:
            netstat_binary = agent_util.which("netstat")

            if not netstat_binary:
                self.log.info("netstat not found")
                status = agent_util.UNSUPPORTED
                msg = "Please install netstat."
                return {}

            if status is agent_util.SUPPORTED:
                ret, output = agent_util.execute_command("%s -ib" % netstat_binary)
                self.log.debug("BANDWIDTH INFO")
                self.log.debug(output)
                if config.get("debug", False):
                    self.log.debug(
                        "#####################################################"
                    )
                    self.log.debug("Bandwidth command 'netstat -ib' output:")
                    self.log.debug(output)
                    self.log.debug(
                        "#####################################################"
                    )

                output = output.splitlines()[1:]
                for line in output:
                    if line == "" or "lo" in line:
                        continue
                    stuff = line.strip().split()
                    iface = stuff[0]
                    add_to_interfaces(iface)

        elif "aix" in sys.platform:
            if not agent_util.which("netstat"):
                self.log.info("netstat not found")
                status = agent_util.UNSUPPORTED
                msg = "Please install netstat."
                return {}

            # Get the list of network devices
            interfaces = []
            ret, output = agent_util.execute_command(
                "netstat -v | grep 'ETHERNET STATISTICS'"
            )
            output = output.strip().split("\n")
            for line in output:
                fields = line.split()
                try:
                    add_to_interfaces(fields[2].strip("(").strip(")"))
                except:
                    pass

            metadata = {}
            metadata["bandwidth.kbytes.in"] = {
                "label": "Kilobytes IN per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }

            metadata["bandwidth.kbytes.out"] = {
                "label": "Kilobytes OUT per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }

            metadata["bandwidth.packets.in"] = {
                "label": "Packets IN per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "packets",
            }

            metadata["bandwidth.packets.out"] = {
                "label": "Packets OUT per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "packets",
            }

            return metadata

        elif "sunos" in sys.platform:
            if not agent_util.which("netstat"):
                self.log.info("netstat not found")
                status = agent_util.UNSUPPORTED
                msg = "Please install netstat."
                return {}

            # Get the list of network devices
            interfaces = []
            ret, output = agent_util.execute_command("netstat -i")
            output = output.strip().split("\n")
            for line in output:
                fields = line.split()
                if not fields:
                    continue
                if fields[0] in ("lo", "inet", "ether", "Name"):
                    continue
                try:
                    add_to_interfaces(fields[0])
                except:
                    pass

            metadata = {}
            metadata["bandwidth.kbytes.in"] = {
                "label": "Kilobytes IN per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }

            metadata["bandwidth.kbytes.out"] = {
                "label": "Kilobytes OUT per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }

            metadata["bandwidth.packets.in"] = {
                "label": "Packets IN per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "packets",
            }

            metadata["bandwidth.packets.out"] = {
                "label": "Packets OUT per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "packets",
            }

            return metadata

        elif "vmware" in sys.platform:
            if not agent_util.which("esxcli"):
                self.log.info("esxcli not found")
                status = agent_util.UNSUPPORTED
                msg = "Please confirm esxcli is installed."
                return {}

            interfaces = []
            ret, out = agent_util.execute_command("esxcli network nic list")
            iface_table = out.split("\n")
            for iface in iface_table:
                # skip the headers, dividers and any empty items
                if iface.startswith("Name") or iface.startswith("--") or iface == "":
                    continue
                add_to_interfaces(iface.split()[0])

            metadata = {}
            metadata["bandwidth.kbytes.in"] = {
                "label": "Kilobytes IN per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }

            metadata["bandwidth.kbytes.out"] = {
                "label": "Kilobytes OUT per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }

            metadata["bandwidth.packets.in"] = {
                "label": "Packets IN per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "packets",
            }

            metadata["bandwidth.packets.out"] = {
                "label": "Packets OUT per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "packets",
            }

            return metadata

        elif "hp-ux" in sys.platform:
            ret, out = agent_util.execute_command("nwmgr -g")
            iface_table = out.splitlines()
            interfaces = []
            for line in iface_table:
                if not line.lower().startswith("lan"):
                    continue
                iface = line.split()
                if iface[1] != "UP":
                    continue
                add_to_interfaces(iface[0])

            metadata = {}
            metadata["bandwidth.kbytes.in"] = {
                "label": "Kilobytes IN per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }

            metadata["bandwidth.kbytes.out"] = {
                "label": "Kilobytes OUT per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }

            metadata["bandwidth.packets.in"] = {
                "label": "Packets IN per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "packets",
            }

            metadata["bandwidth.packets.out"] = {
                "label": "Packets OUT per second",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "packets",
            }

            return metadata

        else:
            # Default Linux options
            if not os.path.exists("/proc/net/dev"):
                self.log.info("/proc/net/dev not found")
                status = agent_util.UNSUPPORTED
                msg = "/proc/net/dev not found"
                return {}

            if status is agent_util.SUPPORTED:
                # get the interfaces
                output = open("/proc/net/dev", "r").read()
                output = output.splitlines()
                if config.get("debug", False):
                    self.log.debug(
                        "#####################################################"
                    )
                    self.log.debug("Content of file '/proc/net/dev':")
                    self.log.debug(str(output))
                    self.log.debug(
                        "#####################################################"
                    )

                for line in output[2:]:
                    stuff = line.strip().split()
                    iface, bytes_read = stuff[0].split(":")
                    add_to_interfaces(iface)

        interfaces = list(interfaces)
        interfaces.sort()

        if status is agent_util.SUPPORTED and not interfaces:
            status = agent_util.MISCONFIGURED
            msg = "No network interfaces found."

        metadata = {}
        metadata["bandwidth.kbytes.in"] = {
            "label": "Kilobytes IN per second",
            "options": interfaces,
            "status": status,
            "error_message": msg,
            "unit": "kB",
        }

        metadata["bandwidth.kbytes.out"] = {
            "label": "Kilobytes OUT per second",
            "options": interfaces,
            "status": status,
            "error_message": msg,
            "unit": "kB",
        }

        metadata["bandwidth.packets.in"] = {
            "label": "Packets IN per second",
            "options": interfaces,
            "status": status,
            "error_message": msg,
            "unit": "packets",
        }

        metadata["bandwidth.packets.out"] = {
            "label": "Packets OUT per second",
            "options": interfaces,
            "status": status,
            "error_message": msg,
            "unit": "packets",
        }

        if "freebsd" not in sys.platform and "darwin" not in sys.platform:
            metadata["bandwidth.monthly.in"] = {
                "label": "Kilobytes IN for the month",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }
            metadata["bandwidth.monthly.out"] = {
                "label": "Kilobytes OUT for the month",
                "options": interfaces,
                "status": status,
                "error_message": msg,
                "unit": "kB",
            }

        return metadata

    def check(self, textkey, interface, config):
        interface_found = False

        if "freebsd" in sys.platform:
            ret, output = agent_util.execute_command("netstat -ib")
            lines = output.splitlines()[1:]

            for line in lines:
                if "lo" in line or line == "":
                    continue
                line = line.split()
                (
                    si,
                    mtu,
                    network,
                    addr,
                    packets_read,
                    ierr,
                    idrop,
                    bytes_read,
                    packets_written,
                    oerr,
                    bytes_written,
                    coll,
                ) = line
                packets_read = int(packets_read)
                packets_written = int(packets_written)
                kbytes_read = int(bytes_read) / 1024
                kbytes_written = int(bytes_written) / 1024

                if si == interface and network.startswith("<Link"):
                    interface_found = True
                    break
        elif "darwin" in sys.platform:
            netstat = agent_util.which("netstat")
            ret, output = agent_util.execute_command("%s -ibn" % netstat)
            lines = output.splitlines()[1:]

            for line in lines:
                if "lo" in line or line == "":
                    continue
                line = line.split()
                si = line[0]
                network = line[2]
                packets_read = int(line[-7])
                bytes_read = int(line[-5])
                packets_written = int(line[-4])
                bytes_written = int(line[-2])
                kbytes_read = bytes_read / 1024
                kbytes_written = bytes_written / 1024

                if si == interface and network.startswith("<Link"):
                    interface_found = True
                    break

        elif "aix" in sys.platform:
            ret, output = agent_util.execute_command(
                'netstat -v %s | grep "^Bytes:"' % interface
            )
            fields = output.split()
            kbytes_written = int(fields[1]) / 1024
            kbytes_read = int(fields[3]) / 1024
            ret, output = agent_util.execute_command(
                'netstat -v %s | grep "^Packets:"' % interface
            )
            fields = output.split()
            packets_written = int(fields[1]) / 1024
            packets_read = int(fields[3]) / 1024
            interface_found = True

        elif "sunos" in sys.platform:
            ret, output = agent_util.execute_command("netstat -i")
            for line in output.strip().split("\n"):
                fields = line.strip().split()
                if not fields:
                    continue
                if fields[0] == interface:
                    interface_found = True
                    packets_read = int(fields[4])
                    packets_written = int(fields[6])
            kbytes_read = 0
            kbytes_written = 0
            ret, output = agent_util.execute_command(
                "kstat -n %s 1 2 | egrep 'bytes64' | uniq" % interface
            )
            for line in output.split("\n"):
                if not line:
                    continue
                if "obytes" in line:
                    fields = line.split()
                    kbytes_read = int(fields[1]) / 1024

                elif "rbytes" in line:
                    fields = line.split()
                    kbytes_written = int(fields[1]) / 1024

        elif "vmware" in sys.platform:
            ret, out = agent_util.execute_command(
                "esxcli network nic stats get -n %s" % interface
            )
            if ret == 0:
                interface_found = True
            iface_stats = {}
            fields = out.split("\n")
            for i in fields:
                trans = i.strip().split(":")
                if len(trans) != 2:
                    continue
                iface_stats[trans[0]] = trans[1].strip()

            kbytes_written = int(iface_stats["Bytes sent"]) / 1024
            kbytes_read = int(iface_stats["Bytes received"]) / 1024
            packets_written = int(iface_stats["Packets sent"])
            packets_read = int(iface_stats["Packets received"])

        elif "hp-ux" in sys.platform:
            interface_found = True
            # NOTE, we need to first divide by 8 to get bytes from octets
            # then divide by 1024 to get KB
            ret, out = agent_util.execute_command("nwmgr --st -c %s" % interface)
            nwmgr = out.splitlines()
            iface_stats = {}
            for line in nwmgr:
                if "=" not in line:
                    continue
                l = line.split("=")
                iface_stats[l[0].strip()] = l[1].strip()
            self.log.debug(iface_stats)

            kbytes_read = (float(iface_stats["Inbound Octets"]) / 8) / 1024
            kbytes_written = (float(iface_stats["Outbound Octets"]) / 8) / 1024
            packets_read = total_pkts = (
                float(iface_stats["Inbound Unicast Packets"])
                + float(iface_stats["Inbound Multicast Packets"])
                + float(iface_stats["Inbound Broadcast Packets"])
            )
            packets_written = total_pkts = (
                float(iface_stats["Outbound Unicast Packets"])
                + float(iface_stats["Outbound Multicast Packets"])
                + float(iface_stats["Outbound Broadcast Packets"])
            )

        else:
            output = open("/proc/net/dev", "r").read()

            self.log.debug("/proc/net/dev output: %s" % str(output))

            output = output.splitlines()

            for line in output[2:]:
                stuff = line.strip().split()
                if not stuff[0].endswith(":"):
                    stuff[0], new_insert = stuff[0].split(":")
                    stuff.insert(1, new_insert)
                else:
                    stuff[0] = stuff[0].rstrip(":")

                iface = stuff[0]
                bytes_read = int(stuff[1])
                bytes_written = int(stuff[9])
                kbytes_read = int(bytes_read) / 1024
                kbytes_written = int(stuff[9]) / 1024
                packets_read = int(stuff[2])
                packets_written = int(stuff[10])

                if interface == iface:
                    interface_found = True
                    break

            # Special handling for monthly bandwidth - each time through we bank the
            # difference in the current reading vs. the previous, taking into account
            # cases where we cross a month boundary and when the byte counters wrap
            if textkey.startswith("bandwidth.monthly"):
                if textkey == "bandwidth.monthly.in":
                    current_bytes = bytes_read
                else:
                    current_bytes = bytes_written

                # First get the cached values
                c = self.get_cache_results(textkey + ":current_bytes", interface)
                previous_bytes = c and c[0][1] or current_bytes
                c = self.get_cache_results(textkey + ":banked_bytes", interface)
                banked_bytes = c and c[0][1] or 0
                c = self.get_cache_results(textkey + ":current_month", interface)
                current_month = c and c[0][1] or datetime.now().month
                c = self.get_cache_results(textkey + ":current_year", interface)
                current_year = c and c[0][1] or datetime.now().year

                now = datetime.now()
                if now.year != current_year or now.month != current_month:
                    # If we"ve crossed a month boundary, zero out bank and reset counters
                    banked_bytes = 0
                    current_year = now.year
                    current_month = now.month
                    previous_bytes = current_bytes

                elif current_bytes < previous_bytes:
                    # The OS counters wrapped, need to handle this
                    banked_bytes += current_bytes
                    previous_bytes = current_bytes

                else:
                    # Standard case, just bank the difference between current and last
                    banked_bytes += current_bytes - previous_bytes
                    previous_bytes = current_bytes

                # Cache the new values
                self.cache_result(
                    textkey + ":current_bytes", interface, current_bytes, replace=True
                )
                self.cache_result(
                    textkey + ":banked_bytes", interface, banked_bytes, replace=True
                )
                self.cache_result(
                    textkey + ":current_month", interface, current_month, replace=True
                )
                self.cache_result(
                    textkey + ":current_year", interface, current_year, replace=True
                )

                return banked_bytes / 1024

        # Because of AIX's interface naming convention, every
        # command provides a different interface name, we need to ignore that
        if "aix" in sys.platform:
            pass
        else:
            if not interface_found:
                self.log.warning("interface %s not found!?" % interface)
                return None

        # try to get the old cache
        cache = self.get_cache_results(textkey, interface)

        # cache our result always
        if textkey == "bandwidth.kbytes.in":
            result = kbytes_read
        elif textkey == "bandwidth.kbytes.out":
            result = kbytes_written
        elif textkey == "bandwidth.packets.in":
            result = packets_read
        elif textkey == "bandwidth.packets.out":
            result = packets_written
        else:
            self.log.error("UNKNOWN BANDWIDTH TEXTKEY- %s" % textkey)
        self.cache_result(textkey, interface, result)

        if not cache:
            return 0.0

        delta, cached_result = cache[0]

        self.log.debug("kbytes read: %d" % kbytes_read)
        self.log.debug("kbytes written: %d" % kbytes_written)
        self.log.debug("packets read: %d" % packets_read)
        self.log.debug("packets written: %d" % packets_written)
        new_value = result - cached_result
        if new_value < 0.0:
            self.log.warning(
                "Metric {} current {} less than cached {} - maybe reboot or counter overflow".format(
                    textkey, result, cached_result
                )
            )
            return None

        return new_value / float(delta)

Youez - 2016 - github.com/yon3zu
LinuXploit