예제 #1
0
    def test_get_device_broker(self):
        netmri = InfobloxNetMRI(**self.opts)
        broker = netmri.get_broker('Device')
        self.assertEquals(broker.__class__.__name__, 'DeviceBroker',
                          "Device broker import error")

        broker = netmri.get_broker('AccessChange')
        self.assertEquals(broker.__class__.__name__, 'AccessChangeBroker',
                          "AccessChangeBroker broker import error")

        broker = netmri.get_broker('ChangedPortNetExplorerInvSummaryGrid')
        self.assertEquals(
            broker.__class__.__name__,
            'ChangedPortNetExplorerInvSummaryGridBroker',
            'ChangedPortNetExplorerInvSummaryGridBroker broker import error ')
예제 #2
0
 def test_check_single_device(self):
     netmri = InfobloxNetMRI(**self.opts)
     broker = netmri.get_broker('Device')
     with patch.object(netmri.session, 'request',
                       side_effect=single_device):
         res = broker.show(DeviceID=1)
         self.assertEquals(res.DeviceID, 1, "Wrong id")
예제 #3
0
 def test_check_return_values(self):
     netmri = InfobloxNetMRI(**self.opts)
     broker = netmri.get_broker('Device')
     with patch.object(netmri.session, 'request', side_effect=devices_list):
         res = broker.index()
         self.assertEquals(res[0].DeviceID, 1, "Wrong id device 1")
         self.assertEquals(res[1].DeviceID, 2, "Wrong id device 2")
예제 #4
0
 def test_get_device(self):
     netmri = InfobloxNetMRI(**self.opts)
     broker = netmri.get_broker('Device')
     with patch.object(netmri, 'session') as mock_request:
         broker.show(DeviceID=2)
         mock_request.request.assert_called_with(
             "post",
             'https://localhost/api/3/devices/show',
             headers={'Content-type': 'application/json'},
             data='{"DeviceID": 2}')
예제 #5
0
class NetMRIEasy(object):
    def __init__(self, debug=False, **kwargs):
        self.debug = debug
        self.api_version = kwargs.get('api_version') or "auto"
        self.host = urlparse(kwargs.get('api_url')).hostname
        self.username = kwargs.get('http_username')
        self.password = kwargs.get('http_password')
        self.job_id = kwargs.get('job_id')
        self.device_id = kwargs.get('device_id')
        self.batch_id = kwargs.get('batch_id')
        self.script_login = kwargs.get('script_login')

        if (not self.job_id) or (not self.device_id) or (not self.batch_id):
            raise RuntimeError(
                'job_id or device_id or batch_id not initialized')

        self.client = InfobloxNetMRI(self.host,
                                     self.username,
                                     self.password,
                                     api_version=self.api_version)

        self.dis_session = self._open_dis_session()
        if not self.script_login == 'false':
            self.cli_connection = self._open_cli_connection()
        self._setup_logging()

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close_session()

    def broker(self, name):
        return self.client.get_broker(name)

    def _setup_logging(self):
        broker = self.broker('Job')
        if hasattr(broker, 'log_custom_message'):

            def remote_log_message(self, severity, message):
                date = datetime.datetime.now()
                brkr = self.broker('Job')
                msg_formatted = "{} [{:<7}] {}".format(
                    date.strftime("%Y-%m-%d %H:%M:%S "),
                    str(severity).upper(), message)
                brkr.log_custom_message(message=msg_formatted,
                                        id=self.batch_id,
                                        jobdetailid=self.job_id,
                                        severity=severity)

            setattr(self.__class__, "remote_log_message", remote_log_message)
        else:

            def remote_log_message(self, severity, message):
                if not hasattr(self, 'cli_connection'):
                    return

                brkr = self._get_cli_broker()
                return brkr.log_message(id=self.dis_session.SessionID,
                                        device_id=self.device_id,
                                        severity=severity,
                                        message=message)

            setattr(self.__class__, "remote_log_message", remote_log_message)

    def _open_cli_connection(self):
        if getattr(self, 'cli_connection', None) and self.cli_connection:
            return self.cli_connection
        return self._get_cli_broker().open(id=self.dis_session.SessionID,
                                           DeviceID=self.device_id)

    def _close_dis_session(self):
        return self.broker('DisSession').close(id=self.dis_session.SessionID)

    def _open_dis_session(self):
        return self.broker('DisSession').open(job_id=self.job_id)

    def send_command(self, command, regex=None):
        if not hasattr(self, 'cli_connection'):
            return

        regex = regex or ""
        result = self._get_cli_broker().send_command(
            id=self.dis_session.SessionID,
            device_id=self.device_id,
            command=command,
            regex=regex)
        if result:
            return result.get('command_response')
        return result

    def send_async_command(self,
                           command,
                           timeout,
                           regex,
                           wait_until_finished=True):
        if not hasattr(self, 'cli_connection'):
            return

        regex = regex or ""
        self._print("Sending asynchronous command ({})".format(command))
        try:
            async_command_result = self._get_cli_broker().send_async_command(
                id=self.dis_session.SessionID,
                device_id=self.device_id,
                command=command,
                timeout=timeout,
                debug=self.debug,
                regex=regex,
            )
            self._ok()
            async_command_id = async_command_result.get('command_response')

            if async_command_id:
                async_command_id = async_command_id.replace(
                    "async_command_id:", "")
            else:
                self._error("Invalid send_async_command response ({})".format(
                    str(async_command_id)))

            if not async_command_id.isdigit():
                self._error("Invalid send_async_command response ({})".format(
                    str(async_command_id)))

            self._print("Received async_command_id {}".format(
                str(async_command_id)))
            self._ok()
            if not wait_until_finished:
                return async_command_id

            delay = 30
            max_delay = 14400 + 900  # DIS max session time plus a little padding (4.25 hours)
            cur_delay = 0
            ok = "async_command_id_status:OK\n"
            error = "async_command_id_status:Error\n"
            while True:
                self._print("Getting the status of async_command_id {}".format(
                    async_command_id))
                res = self._get_cli_broker().get_async_command_status(
                    id=self.dis_session.SessionID,
                    device_id=self.device_id,
                    async_command_id=async_command_id)

                if not res:
                    self._error(
                        "Invalid get_async_command_status response ({})".
                        format(res))
                result = res.get('command_response')

                if ok in result:
                    return result.replace(ok, '')

                if error in result:
                    self._error("Asynchronous command failed {}".format(
                        result.replace(error, '')))

                if cur_delay >= max_delay:
                    self._error(
                        "Timeout waiting for asynchronous command to complete")
                time.sleep(delay)
                cur_delay += delay

        except AttributeError:
            raise RuntimeError(
                "Api version {} not support async commands. Minimal version: 2.10"
                .format(self.client.api_version))

    def get_config(self, sync=True):
        if not hasattr(self, 'cli_connection'):
            return

        self._print(
            "Requesting on demand configuration collection ({})".format(sync))
        traking_id = None
        try:
            res = self.broker('ConfigRevision').get_configs(
                DeviceID=self.device_id)
            traking_id = res.get('TrackingID')

        except RuntimeError as e:
            raise RuntimeError(
                "Api version {} not support this command. Minimal version: 2.10"
                .format(self.client.api_version))
        self._print("Received TrackingID {}".format(traking_id))
        self._ok()
        if not sync:
            return traking_id

        delay = 30
        max_delay = 600
        cur_delay = 0
        while True:
            self._print(
                "Getting the status of TrackingID {}".format(traking_id))
            status_resp = self.broker('ConfigRevision').get_configs_status(
                TrackingID=traking_id)
            if status_resp.get('Status') == "OK":
                return status_resp

            if status_resp.get('Status') == "Error":
                self._error("On demand configuration collection failed")

            if cur_delay >= max_delay:
                self._error(
                    "Timeout waiting for configuration collection to complete")

            time.sleep(delay)
            cur_delay += delay

            self._print("Sending 'Keep Alive CR/LF'")
            self.send_command("NOP:")
            self._ok()

    def set_variable(self, name, value):
        if not hasattr(self, 'cli_connection'):
            return

        command = '${name} ="{value}"'.format(name=name, value=value)
        result = self._get_cli_broker().set_variable(
            id=self.dis_session.SessionID,
            device_id=self.device_id,
            command=command)
        if result:
            return result.get('command_response')
        return result

    def get_template(self, template_name, stage):
        if not hasattr(self, 'cli_connection'):
            return

        result = self._get_cli_broker().get_template(
            id=self.dis_session.SessionID,
            device_id=self.device_id,
            template=template_name,
            stage=(stage or 0))
        if result:
            return result.get('command_response')
        return result

    def get_list_value(self, list_name, key_column, key_value, value_column,
                       default):
        if not hasattr(self, 'cli_connection'):
            return

        result = self._get_cli_broker().get_list_value(
            id=self.dis_session.SessionID,
            device_id=self.device_id,
            list_name=list_name,
            key_column=key_column,
            key_value=key_value,
            value_column=value_column,
            default_value=default)
        if result:
            return result.get('command_response')
        return result

    def generate_issue(self, issue_type_id, severity, **kwargs):
        result = self.broker('IssueAdhoc').generate_issue(
            DeviceID=self.device_id,
            BatchID=self.batch_id,
            Severity=severity,
            IssueTypeID=issue_type_id,
            **kwargs)
        if result:
            return result.get('IssueID')
        return result

    def close_session(self):
        brkr = self.broker('DisSession')
        return brkr.close(SessionID=self.dis_session.SessionID)

    def get_device(self):
        return self.broker('Device').show(DeviceID=self.device_id)

    def log_message(self, severity, message):
        self.remote_log_message(severity, message)

    def _get_cli_broker(self):
        return self.client.get_broker('CliConnection')

    def _print(self, msg):
        if self.debug:
            print(msg)

    def _print_status(self, status):
        if self.debug:
            print(status)

    def _ok(self):
        self._print("OK")

    def _error(self, message):
        print("\n*** ERROR: {} ***\n".format(message))
        sys.exit(-1)
예제 #6
0
defaults = {
    "host": "netmri.yourdomain",
    "username": "******",
    "password": netmri_password,
}

client = InfobloxNetMRI(
    defaults.get("host"),
    defaults.get("username"),
    defaults.get("password"),
)
'''
Below broker is to get device ID from the "Device" broker
'''
dev_broker = client.get_broker("Device")
devices = dev_broker.index(
)  # Indexes all NetMRI devices, but you could limit based on DeviceID or DeviceGroupID
devname = "your-device-name"  # You could always make this some other input, or just index the DeviceID if you know it.
'''
Below iterates through devices from the device broker indexing.  Then, pull out the "DeviceID"
value from the device that matches "devname" and put that DeviceID in the "VlanMember" broker
index method.
'''
for device in devices:
    if devname in str(device.DeviceName):
        print(device.DeviceName)
        dev_id = str(device.DeviceID)
        vlan_mem_broker = client.get_broker(
            "VlanMember")  # Broker for interface VLANs
        vlan_mem_find = vlan_mem_broker.index(
예제 #7
0
args = parser.parse_args()

defaults = {
    "host": "1.2.3.4",
    "username": "******",
    "password": "******",
}

client = InfobloxNetMRI(
    defaults.get("host"),
    defaults.get("username"),
    defaults.get("password"),
)

# get Script broker
broker = client.get_broker('Device')

# get devices
devices = broker.find(op_DeviceName='like',
                      val_c_DeviceName=args.pattern,
                      select=['DeviceID'])

# get Script broker
script_broker = client.get_broker('Script')

# submit the job to the NetMRI
job_id = script_broker.run(
    **{
        'name': args.script_name,
        'device_ids': [x.DeviceID for x in devices],
        '$command': args.command
parser.add_argument('device_name', help="script name")
args = parser.parse_args()

defaults = {
    "host": "1.2.3.4",
    "username": "******",
    "password": "******",
}

client = InfobloxNetMRI(
    defaults.get("host"),
    defaults.get("username"),
    defaults.get("password"),
)

devices_broker = client.get_broker('Device')
device = devices_broker.index(DeviceName=args.device_name,
                              select=['DeviceID', 'DeviceName'])[0]

print(device.DeviceName)

# find the neighbor relationships where our device
# is the source
source_relations = client.get_broker('Neighbor').index(
    DeviceID=device.DeviceID, select=['NeighborDeviceID'])

# find the neighbor relationships where our device
# is the destination.
destination_relations = client.get_broker('Neighbor').index(
    NeighborDeviceID=device.DeviceID, select=[
        'DeviceID',
예제 #9
0
#!/usr/bin/env python

import argparse

from infoblox_netmri.client import InfobloxNetMRI

parser = argparse.ArgumentParser(description='get device ip')
parser.add_argument('device_id', help="device id")
args = parser.parse_args()

defaults = {
    "host": "1.2.3.4",
    "username": "******",
    "password": "******",
}

client = InfobloxNetMRI(
    defaults.get("host"),
    defaults.get("username"),
    defaults.get("password"),
)

# get broker for specific API Object
broker = client.get_broker("Device")

device = broker.show(DeviceID=args.device_id)
print(device.DeviceIPDotted)
예제 #10
0
from infoblox_netmri.client import InfobloxNetMRI

parser = argparse.ArgumentParser(description='update user email')
parser.add_argument('domain', help="user email")
args = parser.parse_args()

defaults = {
    "host": "1.2.3.4",
    "username": "******",
    "password": "******",
}

client = InfobloxNetMRI(
    defaults.get("host"),
    defaults.get("username"),
    defaults.get("password"),
)

auth_users_broker = client.get_broker('AuthUser')
auth_users = auth_users_broker.index(select=['id', 'user_name'])
for user in auth_users:
    print("Current user email: {}".format(user.email))
    # compute email address based on the user name
    email = "{}@{}".format(user.user_name, args.domain)
    data = auth_users_broker.update(
        id=user.id,
        # set or replace the email address for that user
        email=args.email
    )
    print("Updated email: {}".format(data.email))
defaults = {
    "host": "netmri.yourdomain",
    "username": "******",
    "password": netmri_password,
}

client = InfobloxNetMRI(
    defaults.get("host"),
    defaults.get("username"),
    defaults.get("password"),
)

'''
Below broker is to get device ID from the "Device" broker
'''
dev_broker = client.get_broker("Device")
devices = dev_broker.index()
devname = "your-device-name"

'''
Below iterates through devies from the device broker indexing.  Then, pull out the "DeviceID"
value from the device that matches "devname" and put that DeviceID in the "Interface" broker
find method.
'''
for device in devices:
    if devname in str(device.DeviceName):
        dev_id = str(device.DeviceID)
        int_broker = client.get_broker('Interface')
        int_data = int_broker.find(op_DeviceID="=",
                                 val_c_DeviceID=dev_id) # All interfaces for this device ID
        vlan_broker = client.get_broker("IfVlan") # Broker for interface VLANs
예제 #12
0
from infoblox_netmri.client import InfobloxNetMRI

defaults = {
    "host": "1.2.3.4",
    "username": "******",
    "password": "******",
}

client = InfobloxNetMRI(
    defaults.get("host"),
    defaults.get("username"),
    defaults.get("password"),
)

# get broker for interface addr
broker = client.get_broker('IfAddr')

# query interfaces which device id is greater than 20
addrs = broker.find(
    op_DeviceID=">",
    val_c_DeviceID='20',
    select=['DeviceID', 'DeviceName', 'InterfaceID', 'ifIPDotted'])

# get broker for interface remote model
interface_broker = client.get_broker('Interface')
for addr in addrs:
    interface = interface_broker.show(InterfaceID=addr.InterfaceID)
    print("{}    {}".format(addr.ifIPDotted, interface.ifName))