Package Products :: Package DataCollector :: Module PortscanClient |
[hide private]
[frames] | no frames]

# Source Code for Module Products.DataCollector.PortscanClient

      1  ##############################################################################
      2  #
      3  # Copyright (C) Zenoss, Inc. 2007, all rights reserved.
      4  #
      5  # This content is made available according to terms specified in
      6  # License.zenoss under the directory where your Zenoss product is installed.
      7  #
      8  ##############################################################################
      9
     10
     11  __doc__ = """PortscanClient
     12  Performance collector of port-scanning
     13  """
     14
     15  import logging
     16
     17  from twisted.internet import reactor
     18  from twisted.python import failure
     19
     20  import Globals
     21
     22  from Products.ZenUtils import PortScan
     23
     24  log = logging.getLogger("zen.PortscanClient")
     25
     26  from BaseClient import BaseClient
     27
     28 -class PortscanClient(BaseClient):
     29      """
     30      Implement the DataCollector Client interface for port-scanning
     31      """
     32
     33 -    def __init__(self, hostname, ipaddr, options=None, device=None,
     34                   datacollector=None, plugins=[]):
     35          """
     36          Initializer
     37
     38          @param hostname: name of the remote device
     39          @type hostname: string
     40          @param ipaddr: IP address of the remote device
     41          @type ipaddr: string
     42          @param options: optparse options
     43          @type options: optparse options object
     44          @param device: DMD device object
     45          @type device: device object
     46          @param datacollector: performance data collector object
     47          @type datacollector: datacollector object
     48          @param plugins: performance data collector plugin
     49          @type plugins: list of plugin objects
     50          """
     51          BaseClient.__init__(self, device, datacollector)
     52          self.hostname = hostname
     53          self.options = options
     54          self.plugins = plugins
     55          self.results = []
     56
     57          maxPort = getattr(device,'zIpServiceMapMaxPort', 1024)
     58          self.portRange = (1, maxPort)
     59
     60          #self.portList = getattr(device,'zPortscanPortList', [])
     61          self.portList = []
     62
     63          if self.portList:
     64              kwds = {'portList': self.portList}
     65          else:
     66              kwds = {'portRange': self.portRange}
     67          kwds.update(dict(timeout=self.options.portscantimeout))
     68          self.scanner = PortScan.Scanner(ipaddr, **kwds)
     69
     70
     71 -    def run(self):
     72          """
     73          Start portscan collection.
     74          """
     75          for plugin in self.plugins:
     76              log.debug("Sending queries for plugin %s", plugin.name())
     77              d = self.scanner.prepare()
     78              d.addCallback(self._cbScanComplete, plugin)
     79              d.addErrback(self._ebScanError, plugin)
     80
     81
     82 -    def _cbScanComplete(self, unused, plugin):
     83          """
     84          Start portscan collection.
     85
     86          @param unused: unused (unused)
     87          @type unused: object
     88          @param plugin: performance data collector plugin
     89          @type plugin: plugin object
     90          """
     91          log.debug("Received plugin:%s getOids", plugin.name())
     92          self.clientFinished(plugin)
     93
     94
     95 -    def _ebScanError( self, err, plugin):
     96          """
     97          Handle an error generated by one of our requests.
     98
     99          @param err: result from the collection run
    100          @type err: result or Exception
    101          @param plugin: performance data collector plugin
    102          @type plugin: plugin object
    103          """
    104          self.clientFinished(plugin)
    105          log.debug('Device %s plugin %s %s', self.hostname, plugin.name(), err)
    106          if isinstance(err, failure.Failure):
    107              trace = err.getTraceback()
    108          else:
    109              trace = log.getException(err)
    110          log.error(
    111              """Device %s plugin %s received an unexpected error: %s""",
    112              self.hostname, plugin.name(), trace,
    113          )
    114
    115
    116 -    def getResults(self):
    117          """
    118          ZenUtils.PortScan records open ports in a list that are the
    119          values for a key in a dict where the key is the IP address
    120          scanned.
    121
    122          For example, if we scan host 10.0.4.55 and ports 22 and 80 are
    123          open, getSuccesses() will return the following:
    124
    125              {'10.0.4.55': [22, 80]}
    126
    127          @return: results
    128          @rtype: list of strings
    129          """
    130          return self.results
    131
    132
    133 -    def clientFinished(self, plugin):
    134          """
    135          Tell the datacollector that we are all done.
    136
    137          @param plugin: performance data collector plugin
    138          @type plugin: plugin object
    139          """
    140          log.info("portscan client finished collection for %s" % self.hostname)
    141          # ApplyDataMap.processClient() expect an iterable with two
    142          # elements: the plugin name and the results, so we set this
    143          # here.
    144          self.results.append((plugin, self.scanner.getSuccesses()))
    145          if self.datacollector:
    146              self.datacollector.clientFinished(self)
    147          else:
    148              reactor.stop()
    149
    150
    151 -def buildOptions(parser=None, usage=None):
    152      """
    153      Create the command-line options list
    154      """
    155
    156      if not usage:
    157          usage = "%prog [options] hostname[:port] oids"
    158
    159      if not parser:
    160          from optparse import OptionParser
    161          parser = OptionParser(usage=usage)
    162      # XXX this function may need options later, so we'll keep this here
    163      # as a reminder for now
    164      #parser.add_option('--snmpCommunity',
    165      #            dest='snmpCommunity',
    166      #            default=defaultSnmpCommunity,
    167      #            help='Snmp Community string')
    168
    169
    170  if __name__ == "__main__":
    171      import sys
    172      sys.path.extend([
    173          '/usr/local/zenoss/Products/DataCollector/plugins',
    174      ])
    175      import pprint
    176      from zenoss.portscan import IpServiceMap
    177
    178      logging.basicConfig()
    179      log = logging.getLogger()
    180      log.setLevel(20)
    181      ipmap = IpServiceMap.IpServiceMap()
    182      psc = PortscanClient("localhost", '127.0.0.1', plugins=[ipmap,])
    183      psc.run()
    184      reactor.run()
    185      pprint.pprint(psc.getResults())
    186