Exemplo n.º 1
0
    def add_device(self, uid=None, ip=None, hostname=None, device_class=None, snmp_port=161, snmp_community="public",
                   hw_manufacturer="", hw_productname="", os_manufacturer="", os_productname="",
                   production_state="production", comments="", collector="localhost", location="", systems=[], groups=[]):
        """
        Add a device
        """
        if uid is None:
            status = False
            data = "Invalid uid: None"
            return status, data
        else:
            if not is_valid_ip(uid) and not is_valid_hostname(uid):
                status = False
                data = "Uid is not a valid IP address or FQDN"
                return status, data
            else:
                device_name = uid

        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if production_state not in PRODUCTION_STATES:
            status = False
            data = "Not a valid production state: %s\nPlease use one of: %s" % (production_state, PRODUCTION_STATES.keys())
            return status, data
        else:
            production_state = PRODUCTION_STATES[production_state]

        # FIXME: need to check for existence of the device class
        # Should prevent ObjectNotFoundExceptions from ZenOSS

        params = {
            'title': hostname,
            'manageIp': ip,
            'model': True,
            'productionState': production_state,
            'comments': comments,
            'collector': collector,
            'snmpPort': snmp_port,
            'snmpCommunity': snmp_community,
            'hwManufacturer': hw_manufacturer,
            'hwProductName': hw_productname,
            'osManufacturer': os_manufacturer,
            'osProductName': os_productname,
            'locationPath': location,
            'systemPaths': systems,
            'groupPaths': groups,
        }
        resp = self._add_device(device_name, device_class, params)
        if resp['success']:
            status = True
            data = []
        else:
            status = False
            data = resp['msg']

        return status, data
Exemplo n.º 2
0
    def add_device(self, uid=None, ip=None, hostname=None, device_class=None, snmp_port=161, snmp_community="public",
                   hw_manufacturer="", hw_productname="", os_manufacturer="", os_productname="",
                   production_state="production", comments="", collector="localhost", location="", systems=[], groups=[]):
        """
        Add a device
        """
        if uid is None:
            status = False
            data = "Invalid uid: None"
            return status, data
        else:
            if not is_valid_ip(uid) and not is_valid_hostname(uid):
                status = False
                data = "Uid is not a valid IP address or FQDN"
                return status, data
            else:
                device_name = uid

        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if production_state not in PRODUCTION_STATES:
            status = False
            data = "Not a valid production state: %s\nPlease use one of: %s" % (production_state, PRODUCTION_STATES.keys())
            return status, data
        else:
            production_state = PRODUCTION_STATES[production_state]

        # FIXME: need to check for existence of the device class
        # Should prevent ObjectNotFoundExceptions from ZenOSS

        params = {
            'title': hostname,
            'manageIp': ip,
            'model': True,
            'productionState': production_state,
            'comments': comments,
            'collector': collector,
            'snmpPort': snmp_port,
            'snmpCommunity': snmp_community,
            'hwManufacturer': hw_manufacturer,
            'hwProductName': hw_productname,
            'osManufacturer': os_manufacturer,
            'osProductName': os_productname,
            'locationPath': location,
            'systemPaths': systems,
            'groupPaths': groups,
        }
        resp = self._add_device(device_name, device_class, params)
        if resp['success']:
            status = True
            data = []
        else:
            status = False
            data = resp['msg']

        return status, data
Exemplo n.º 3
0
    def set_production_state(self, ip=None, state=None):
        """
        Set device <uid> in production state <state>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if state not in PRODUCTION_STATES:
            status = False
            data = "Not a valid production state: %s\nPlease use one of: %s" % (state, PRODUCTION_STATES.keys())
            return status, data

        status, data = self.get_uid_by_ip(ip)
        if status:
            params = {'productionState': PRODUCTION_STATES[state]}
            resp = self._set_info(data, params)['result']
            if resp['success']:
                status = True
                data = []
            else:
                status = False
                data = resp['msg']

        return status, data
Exemplo n.º 4
0
def main(ip_address, subnet_mask):
    """
    Validates the Ip and mask passed in
    """
    error = 400
    if utils.is_valid_ipv6(ip_address):
        try:
            if int(subnet_mask) < 129:
                return ipv6_subnet_calc(ip_address, subnet_mask)
            else:
                print("Invalid Subnet Mask")
        except ValueError:
            print("Invalid Subnet Mask")
    elif utils.is_valid_ip(ip_address):
        if utils.is_valid_subnet_mask(subnet_mask):
            return ipv4_subnet_calc(ip_address, subnet_mask, False)

        try:
            if int(subnet_mask) < 32 and int(subnet_mask) > 0:
                return ipv4_subnet_calc(ip_address, subnet_mask, True)
            else:
                print("Invalid Subnet Mask")
        except ValueError:
            print("Invalid Subnet Mask")
    return error
Exemplo n.º 5
0
    def set_priority(self, ip=None, priority=None):
        """
        Set device <ip> to priority <priority>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if priority not in PRIORITIES:
            status = False
            data = "Not a valid priority: %s\nPlease use one of: %s" % (priority, PRIORITIES.keys())
            return status, data

        status, data = self.get_uid_by_ip(ip)
        if status:
            params = {'priority': PRIORITIES[priority]}
            resp = self._set_info(data, params)['result']
            if resp['success']:
                status = True
                data = []
            else:
                status = False
                data = resp['msg']

        return status, data
Exemplo n.º 6
0
    def set_priority(self, ip=None, priority=None):
        """
        Set device <ip> to priority <priority>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if priority not in PRIORITIES:
            status = False
            data = "Not a valid priority: %s\nPlease use one of: %s" % (priority, PRIORITIES.keys())
            return status, data

        status, data = self.get_uid_by_ip(ip)
        if status:
            params = {'priority': PRIORITIES[priority]}
            resp = self._set_info(data, params)['result']
            if resp['success']:
                status = True
                data = []
            else:
                status = False
                data = resp['msg']

        return status, data
Exemplo n.º 7
0
    def remove_device(self, ip=None, keep_data=False):
        """
        Remove a single device as specified by <ip>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        status, data = self.get_uid_by_ip(ip)
        if not status:
            return status, data

        hashcheck = 1
        action = 'delete'
        delete_events = keep_data
        delete_perfs = keep_data
        params = {}
        uids = data
        resp = self._remove_devices(uids, hashcheck, action, delete_events, delete_perfs, params)
        if resp['success']:
            status = True
            data = []
        else:
            status = False
            data = resp['msg']

        return status, data
Exemplo n.º 8
0
    def get_devices_by_ip(self, ip=None):
        """
        Get all devices matching <ip>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        params = {'ipAddressString': ip}
        uid = '/zport/dmd/Devices'
        resp = self._get_devices(uid, params)
        if resp['success']:
            count = int(resp['totalCount'])
            status = True
            data = resp['devices']
        else:
            status = False
            data = resp['msg']
            return status, data

        # remove partial matches from the result
        d = []
        if count > 1:
            for item in data:
                if item['ipAddressString'] == ip:
                    d.append(item)
            data = d

        return status, data
Exemplo n.º 9
0
    def add_event(self, ip=None, summary='', component='', severity='', evclasskey='', evclass=''):
        """
        Send an event to Zenoss
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if severity not in SEVERITIES:
            status = False
            data = "Not a valid severity: %s\nPlease use one of: %s" % (severity, SEVERITIES.keys())
            return status, data
        else:
            severity = SEVERITIES[severity]

        resp = self._add_event(summary, ip, component, severity, evclasskey, evclass)['result']
        if resp['success']:
            status = True
            data = []
        else:
            status = False
            data = resp['msg']

        return status, data
Exemplo n.º 10
0
    def set_production_state(self, ip=None, state=None):
        """
        Set device <uid> in production state <state>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if state not in PRODUCTION_STATES:
            status = False
            data = "Not a valid production state: %s\nPlease use one of: %s" % (state, PRODUCTION_STATES.keys())
            return status, data

        status, data = self.get_uid_by_ip(ip)
        if status:
            params = {'productionState': PRODUCTION_STATES[state]}
            resp = self._set_info(data, params)['result']
            if resp['success']:
                status = True
                data = []
            else:
                status = False
                data = resp['msg']

        return status, data
Exemplo n.º 11
0
    def add_event(self, ip=None, summary='', component='', severity='', evclasskey='', evclass=''):
        """
        Send an event to Zenoss
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if severity not in SEVERITIES:
            status = False
            data = "Not a valid severity: %s\nPlease use one of: %s" % (severity, SEVERITIES.keys())
            return status, data
        else:
            severity = SEVERITIES[severity]

        # get the uid for the given IP
        status, data = self.get_uid_by_ip(ip)
        if status:
            uid = str(data)
            resp = self._add_event(summary, uid, component, severity, evclasskey, evclass)['result']
            if resp['success']:
                status = True
                data = []
            else:
                status = False
                data = resp['msg']

        return status, data
Exemplo n.º 12
0
    def get_devices_by_ip(self, ip=None):
        """
        Get all devices matching <ip>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        params = {'ipAddressString': ip}
        uid = '/zport/dmd/Devices'
        resp = self._get_devices(uid, params)
        if resp['success']:
            count = int(resp['totalCount'])
            status = True
            data = resp['devices']
        else:
            status = False
            data = resp['msg']
            return status, data

        # remove partial matches from the result
        d = []
        if count > 1:
            for item in data:
                if item['ipAddressString'] == ip:
                    d.append(item)
            data = d

        return status, data
Exemplo n.º 13
0
    def remove_device(self, ip=None, keep_data=False):
        """
        Remove a single device as specified by <ip>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        status, data = self.get_uid_by_ip(ip)
        if not status:
            return status, data

        hashcheck = 1
        action = 'delete'
        delete_events = keep_data
        delete_perfs = keep_data
        params = {}
        uids = data
        resp = self._remove_devices(uids, hashcheck, action, delete_events, delete_perfs, params)
        if resp['success']:
            status = True
            data = []
        else:
            status = False
            data = resp['msg']

        return status, data
Exemplo n.º 14
0
 def __init__(self, request, handler, **kwargs):
     if handler.im_class.__name__ in set_userId:
         data = request.data
         sip = data.get('user')
         if not re.match(r"(\w{8}(-\w{4}){3}-\w{12}?)", sip) and not is_valid_ip(sip):
             user_info = self.model(deviceID=kwargs['deviceID'])
             user_list = user_info.get_user_info(sip)
             if len(user_list) == 1:
                 data['user'] = user_list[0]
                 logger.info('api:USDC body:{}'.format(json.dumps(data)))
             else:
                 raise APIDataNotFound('username:{} parase error with user_list:{}'.format(sip, user_list), 1)
Exemplo n.º 15
0
 def process_request(cls, request):
     tz = request.session.get('django_timezone')
     if not tz:
         # use the default timezone (settings.TIME_ZONE) for localhost
         tz = timezone.get_default_timezone()
         client_ip = get_ip_address_from_request(request)
         ip_addresses = client_ip.split(',')
         for ip in ip_addresses:
             if is_valid_ip(ip) and not is_local_ip(ip):
                 response = cls.reader.city(ip)
                 tz = response.location.time_zone
     if tz:
         timezone.activate(tz)
         request.session['django_timezone'] = str(tz)
     else:
         timezone.deactivate()
Exemplo n.º 16
0
    def update_device(self, uid=None, ip=None, hostname=None, device_class=None, snmp_port=161, snmp_community="public",
                      hw_manufacturer="", hw_productname="", os_manufacturer="", os_productname="",
                      production_state="production", comments="", collector="localhost", location="", systems=[], groups=[]):
        """
        Update device registration
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if production_state not in PRODUCTION_STATES:
            status = False
            data = "Not a valid production state: %s\nPlease use one of: %s" % (production_state, PRODUCTION_STATES.keys())
            return status, data

        # check if IP address is already known to zenoss, if not bail out
        status, data = self.get_devices_by_ip(ip)
        if status:
            data_len = len(data)
            if data_len == 0:
                status = False
                data = "IP address (%s) not found\nYou can't change a nodes IP address with zenossctl" % ip
                return status, data
            elif data_len == 1:
                # setup the uid as it was in the first place
                uid = data[0]['uid'].rsplit("/", 1)[1]
            else:
                status = False
                data = "Expected 1 device but found %s devices" % data_len
                return status, data
        else:
            return status, data

        # FIXME
        # check if device class exists

        status, data = self.remove_device(ip, keep_data=True)
        if status and uid is not None:
            status, data = self.add_device(uid, ip, hostname, device_class, snmp_port, snmp_community,
                                           hw_manufacturer, hw_productname, os_manufacturer, os_productname,
                                           production_state, comments, collector, location, systems, groups)

        return status, data
Exemplo n.º 17
0
    def update_device(self, uid=None, ip=None, hostname=None, device_class=None, snmp_port=161, snmp_community="public",
                      hw_manufacturer="", hw_productname="", os_manufacturer="", os_productname="",
                      production_state="production", comments="", collector="localhost", location="", systems=[], groups=[]):
        """
        Update device registration
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        if production_state not in PRODUCTION_STATES:
            status = False
            data = "Not a valid production state: %s\nPlease use one of: %s" % (production_state, PRODUCTION_STATES.keys())
            return status, data

        # check if IP address is already known to zenoss, if not bail out
        status, data = self.get_devices_by_ip(ip)
        if status:
            data_len = len(data)
            if data_len == 0:
                status = False
                data = "IP address (%s) not found\nYou can't change a nodes IP address with zenossctl" % ip
                return status, data
            elif data_len == 1:
                # setup the uid as it was in the first place
                uid = data[0]['uid'].rsplit("/", 1)[1]
            else:
                status = False
                data = "Expected 1 device but found %s devices" % data_len
                return status, data
        else:
            return status, data

        # FIXME
        # check if device class exists

        status, data = self.remove_device(ip, keep_data=True)
        if status and uid is not None:
            status, data = self.add_device(uid, ip, hostname, device_class, snmp_port, snmp_community,
                                           hw_manufacturer, hw_productname, os_manufacturer, os_productname,
                                           production_state, comments, collector, location, systems, groups)

        return status, data
Exemplo n.º 18
0
    def remodel(self, ip=None):
        """
        Trigger a remodel job for device <ip>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        status, data = self.get_uid_by_ip(ip)
        if status:
            resp = self._remodel(data)['result']
            if resp['success']:
                status = True
                data = []
            else:
                status = False
                data = resp['msg']

        return status, data
Exemplo n.º 19
0
    def remodel(self, ip=None):
        """
        Trigger a remodel job for device <ip>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        status, data = self.get_uid_by_ip(ip)
        if status:
            resp = self._remodel(data)['result']
            if resp['success']:
                status = True
                data = []
            else:
                status = False
                data = resp['msg']

        return status, data
Exemplo n.º 20
0
 def reload_camera(self, json_obj, connection, db):
     """
     Generation of the file devices.conf located in /etc/domoleaf by default.
     """
     camera_file = open(CAMERA_CONF_FILE, 'w');
     query = "SELECT room_device_id, addr, plus1 FROM room_device WHERE protocol_id = 6";
     res = self.sql.mysql_handler_personnal_query(query, db);
     for r in res:
         ip = str(r[1]);
         if r[1] and utils.is_valid_ip(ip):
             camera_file.write("location /device/"+str(r[0]));
             camera_file.write("/ {\n")
             camera_file.write("\tproxy_buffering off;\n")
             camera_file.write("\tproxy_pass http://"+ip);
             if str(r[2]).isdigit():
                 camera_file.write(":"+str(r[2])+"/;\n}\n\n");
             else:
                 camera_file.write(":/;\n}\n\n");
     camera_file.close();
     call(["service", "nginx", "restart"]);
Exemplo n.º 21
0
    def get_uid_by_ip(self, ip=None):
        """
        Get the uid for device <ip>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        status, data = self.get_devices_by_ip(ip)
        if status:
            data_len = len(data)
            if data_len == 0:
                data = []
            elif data_len == 1:
                data = data[0]['uid']
            else:
                data = "Expected 1 uid but found %s uids" % data_len
        else:
            data = data['msg']

        return status, data
Exemplo n.º 22
0
    def get_uid_by_ip(self, ip=None):
        """
        Get the uid for device <ip>
        """
        if not is_valid_ip(ip):
            status = False
            data = "Not a valid IP address: %s" % ip
            return status, data

        status, data = self.get_devices_by_ip(ip)
        if status:
            data_len = len(data)
            if data_len == 0:
                data = []
            elif data_len == 1:
                data = data[0]['uid']
            else:
                data = "Expected 1 uid but found %s uids" % data_len
        else:
            data = data['msg']

        return status, data
Exemplo n.º 23
0
 def testValidIP(self):
     result = utils.is_valid_ip('192.22.123.1')
     self.assertTrue(result)
Exemplo n.º 24
0
 def testInvalidIPSlot4(self):
     result = utils.is_valid_ip('192.256.1.')
     self.assertFalse(result)
Exemplo n.º 25
0
 def testInvalidIPSlot1(self):
     result = utils.is_valid_ip('1920.251.123.1')
     self.assertFalse(result)
Exemplo n.º 26
0
        print("%s client application, version %s" %
              (CLIENT_APP_NAME, CLIENT_APP_VERSION))
        print("Connect on %s at %s\n" %
              (now.strftime("%a %d %b %Y"), now.strftime("%H:%M:%S")))
        print("For more information, type 'help'. 'exit' or 'quit' to quit.\n")

    @classmethod
    def help(cls):
        """Show client help"""
        print("\n********************* HELP **********************\n")
        print("This is the help you asked for. Read this carefully!")
        try:
            with open(HELP_FILE, 'r') as _file:
                print(_file.read())
        except FileNotFoundError:
            pass
        print("\n*************************************************\n")

    def __del__(self):
        self.close_connection()


# main
if __name__ == '__main__':
    args = utils.parse_client_args()
    if utils.is_valid_ip(args.host):
        client = FDB_Client(args.user, args.host, args.port)
        client.run()
    else:
        print("ERROR: Invalid IP address")
Exemplo n.º 27
0
 def proxy_ip(self):
     if self._proxy_ip == 'auto':
         return self.proxy.get_ip()
     if not is_valid_ip(self._proxy_ip):
         raise ConfigError('invalid proxy_ip %s' % self._proxy_ip)
     return self._proxy_ip
Exemplo n.º 28
0
 def sub_1(self, sub):
     return list(set([ip for ip in sub if is_valid_ip(ip)]))