免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3903 | 回复: 3
打印 上一主题 下一主题

请教zenoss的学习方法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-08-31 14:20 |只看该作者 |倒序浏览
看了下zenoss-api_2.5.0,变量好多,模块也多,
怎么入手啊,求教{:3_200:}

论坛徽章:
0
2 [报告]
发表于 2011-09-01 10:11 |只看该作者
  1. ###########################################################################
  2. #
  3. # This program is part of Zenoss Core, an open source monitoring platform.
  4. # Copyright (C) 2007, Zenoss Inc.
  5. #
  6. # This program is free software; you can redistribute it and/or modify it
  7. # under the terms of the GNU General Public License version 2 as published by
  8. # the Free Software Foundation.
  9. #
  10. # For complete information please visit: http://www.zenoss.com/oss/
  11. #
  12. ###########################################################################

  13. import sys
  14. import os
  15. import time
  16. import socket
  17. import ip
  18. import icmp
  19. import errno
  20. import logging
  21. log = logging.getLogger("zen.Ping")

  22. from twisted.internet import reactor, defer
  23. from twisted.spread import pb

  24. class PermissionError(Exception):
  25.     """Not permitted to access resource."""

  26. class IpConflict(Exception):
  27.     """Pinging two jobs simultaneously with different hostnames but the same IP"""

  28. class PingJob(pb.Copyable, pb.RemoteCopy):
  29.     """
  30.     Class representing a single target to be pinged.
  31.     """
  32.     def __init__(self, ipaddr, hostname="", status=0, unused_cycle=60):
  33.         self.parent = False
  34.         self.ipaddr = ipaddr
  35.         self.hostname = hostname
  36.         self.status = status
  37.         self.reset()


  38.     def reset(self):
  39.         self.deferred = defer.Deferred()
  40.         self.rrt = 0
  41.         self.start = 0
  42.         self.sent = 0
  43.         self.message = ""
  44.         self.severity = 5
  45.         self.inprocess = False
  46.         self.pathcheck = 0
  47.         self.eventState = 0


  48.     def checkpath(self):
  49.         if self.parent:
  50.             return self.parent.checkpath()


  51.     def routerpj(self):
  52.         if self.parent:
  53.             return self.parent.routerpj()

  54. pb.setUnjellyableForClass(PingJob, PingJob)


  55. plog = logging.getLogger("zen.Ping")
  56. class Ping(object):   
  57.     """
  58.     Class that provides asyncronous icmp ping.
  59.     """
  60.    
  61.     def __init__(self, tries=2, timeout=2, sock=None):
  62.         self.reconfigure(tries, timeout)
  63.         self.procId = os.getpid()
  64.         self.jobqueue = {}
  65.         self.pktdata = 'zenping %s %s' % (socket.getfqdn(), self.procId)
  66.         self.createPingSocket(sock)


  67.     def reconfigure(self, tries=2, timeout=2):
  68.         self.tries = tries
  69.         self.timeout = timeout


  70.     def createPingSocket(self, sock):
  71.         """make an ICMP socket to use for sending and receiving pings"""
  72.         socketargs = socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP
  73.         if sock is None:
  74.             try:
  75.                 s = socket
  76.                 self.pingsocket = s.socket(*socketargs)
  77.             except socket.error, e:
  78.                 err, msg = e.args
  79.                 if err == errno.EACCES:
  80.                     raise PermissionError("must be root to send icmp.")
  81.                 raise e
  82.         else:
  83.             self.pingsocket = socket.fromfd(sock, *socketargs)
  84.             os.close(sock)
  85.         self.pingsocket.setblocking(0)
  86.         reactor.addReader(self)

  87.     def fileno(self):
  88.         return self.pingsocket.fileno()

  89.     def doRead(self):
  90.         self.recvPackets()

  91.     def connectionLost(self, unused):
  92.         reactor.removeReader(self)
  93.         self.pingsocket.close()

  94.     def logPrefix(self):
  95.         return None

  96.     def sendPacket(self, pingJob):
  97.         """Take a pingjob and send an ICMP packet for it"""
  98.         #### sockets with bad addresses fail
  99.         try:
  100.             pkt = icmp.Echo(self.procId, pingJob.sent, self.pktdata)
  101.             buf = icmp.assemble(pkt)
  102.             pingJob.start = time.time()
  103.             plog.debug("send icmp to '%s'", pingJob.ipaddr)
  104.             self.pingsocket.sendto(buf, (pingJob.ipaddr, 0))
  105.             reactor.callLater(self.timeout, self.checkTimeout, pingJob)
  106.             pingJob.sent += 1
  107.             current = self.jobqueue.get(pingJob.ipaddr, None)
  108.             if current:
  109.                 if pingJob.hostname != current.hostname:
  110.                     raise IpConflict("Host %s and %s are both using ip %s" %
  111.                                      (pingJob.hostname,
  112.                                       current.hostname,
  113.                                       pingJob.ipaddr))
  114.             self.jobqueue[pingJob.ipaddr] = pingJob
  115.         except (SystemExit, KeyboardInterrupt): raise
  116.         except Exception, e:
  117.             pingJob.rtt = -1
  118.             pingJob.message = "%s sendto error %s" % (pingJob.ipaddr, e)
  119.             self.reportPingJob(pingJob)


  120.     def recvPackets(self):
  121.         """receive a packet and decode its header"""
  122.         while reactor.running:
  123.             try:
  124.                 data, (host, port) = self.pingsocket.recvfrom(1024)
  125.                 if not data: return
  126.                 ipreply = ip.disassemble(data)
  127.                 try:
  128.                     icmppkt = icmp.disassemble(ipreply.data)
  129.                 except ValueError:
  130.                     plog.debug("checksum failure on packet %r", ipreply.data)
  131.                     try:
  132.                         icmppkt = icmp.disassemble(ipreply.data, 0)
  133.                     except ValueError:
  134.                         continue            # probably Unknown type
  135.                 except Exception, ex:
  136.                     plog.debug("Unable to decode reply packet payload %s", ex)
  137.                     continue
  138.                 sip =  ipreply.src
  139.                 if (icmppkt.get_type() == icmp.ICMP_ECHOREPLY and
  140.                     icmppkt.get_id() == self.procId and
  141.                     self.jobqueue.has_key(sip)):
  142.                     plog.debug("echo reply pkt %s %s", sip, icmppkt)
  143.                     self.pingJobSucceed(self.jobqueue[sip])
  144.                 elif icmppkt.get_type() == icmp.ICMP_UNREACH:
  145.                     try:
  146.                         origpkt = icmppkt.get_embedded_ip()
  147.                         dip = origpkt.dst
  148.                         if (origpkt.data.find(self.pktdata) > -1
  149.                             and self.jobqueue.has_key(dip)):
  150.                             self.pingJobFail(self.jobqueue[dip])
  151.                     except ValueError, ex:
  152.                         plog.warn("failed to parse host unreachable packet")
  153.                 else:
  154.                     plog.debug("unexpected pkt %s %s", sip, icmppkt)
  155.             except (SystemExit, KeyboardInterrupt): raise
  156.             except socket.error, err:
  157.                 errnum, errmsg = err.args
  158.                 if errnum == errno.EAGAIN:
  159.                     return
  160.                 raise err
  161.             except Exception, ex:
  162.                 log.exception("receiving packet error: %s" % ex)


  163.     def pingJobSucceed(self, pj):
  164.         """PingJob completed successfully.
  165.         """
  166.         plog.debug("pj succeed for %s", pj.ipaddr)
  167.         pj.rtt = time.time() - pj.start
  168.         pj.message = "ip %s is up" % (pj.ipaddr)
  169.         self.reportPingJob(pj)


  170.     def pingJobFail(self, pj):
  171.         """PingJob has failed remove from jobqueue.
  172.         """
  173.         plog.debug("pj fail for %s", pj.ipaddr)
  174.         pj.rtt = -1
  175.         pj.message = "ip %s is down" % (pj.ipaddr)
  176.         self.reportPingJob(pj)


  177.     def reportPingJob(self, pj):
  178.         if str(pj.message).endswith("is down"):
  179.             cmdPing="ping "+pj.ipaddr+" -c 1"
  180.             flag=os.system(cmdPing)
  181.             if int(flag)==0:
  182.                 pj.rtt = time.time() - pj.start
  183.                 pj.message="ip "+pj.ipaddr+" is up"
  184.         try:
  185.             del self.jobqueue[pj.ipaddr]
  186.         except KeyError:
  187.             pass
  188.         # also free the deferred from further reporting
  189.         if pj.rtt < 0:
  190.             pj.deferred.errback(pj)
  191.         else:
  192.             pj.deferred.callback(pj)


  193.     def checkTimeout(self, pj):
  194.         if self.jobqueue.has_key(pj.ipaddr):
  195.             now = time.time()
  196.             if now - pj.start > self.timeout:
  197.                 if pj.sent >= self.tries:
  198.                     plog.debug("pj timeout for %s", pj.ipaddr)
  199.                     self.pingJobFail(pj)
  200.                 else:
  201.                     self.sendPacket(pj)
  202.             else:
  203.                 plog.debug("calling checkTimeout needlessly for %s", pj.ipaddr)

  204.     def jobCount(self):
  205.         return len(self.jobqueue)

  206.     def ping(self, ip):
  207.         "Ping the ip and return the result in a deferred"
  208.         pj = PingJob(ip)
  209.         self.sendPacket(pj)
  210.         return pj.deferred


  211. def _printResults(results, start):
  212.     good = [pj for s, pj in results if s and pj.rtt >= 0]
  213.     bad = [pj for s, pj in results if s and pj.rtt < 0]
  214.     if good: print "Good ips: %s" % " ".join([g.ipaddr for g in good])
  215.     if bad: print "Bad ips: %s" % " ".join([b.ipaddr for b in bad])
  216.     print "Tested %d ips in %.1f seconds" % (len(results), time.time() - start)
  217.     reactor.stop()

  218. if __name__ == "__main__":
  219.     ping = Ping()
  220.     logging.basicConfig()
  221.     log = logging.getLogger()
  222.     log.setLevel(10)
  223.     if len(sys.argv) > 1: targets = sys.argv[1:]
  224.     else: targets = ("127.0.0.1",)
  225.     lst = defer.DeferredList(map(ping.ping, targets), consumeErrors=True)
  226.     lst.addCallback(_printResults, time.time())
  227.     reactor.run()
复制代码
zenoss-api_2.5.0\api\Products.ZenStatus.AsyncPing-module.html
ip 和icmp模块在哪里可以找得到啊

论坛徽章:
0
3 [报告]
发表于 2011-09-01 11:09 |只看该作者
回复 1# 307183927
自带了 在externallibs里。 这里也有 http://pypi.python.org/pypi/pyip/

论坛徽章:
0
4 [报告]
发表于 2011-09-01 11:53 |只看该作者
真详细,地址都给出来了,‘106033177’ 谢谢了{:3_193:}
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP