Пример #1
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")
Пример #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_delete_with_string(self):
     netmri = InfobloxNetMRI(**self.opts)
     with patch.object(netmri, 'session') as mock_request:
         netmri.delete('job', '321')
         mock_request.request.assert_called_with(
             "delete",
             'https://localhost/api/3.1/jobs/321',
             headers={'Content-type': 'application/json'},
             data=None)
Пример #4
0
 def test_show(self):
     netmri = InfobloxNetMRI(**self.opts)
     with patch.object(netmri, 'session') as mock_request:
         netmri.show('job', 123)
         mock_request.request.assert_called_with(
             "get",
             'https://localhost/api/3.1/jobs/123',
             headers={'Content-type': 'application/json'},
             data=None)
Пример #5
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}')
Пример #6
0
    def test_init_ssl_verify_bool(self):
        netmri = InfobloxNetMRI(**self.opts)
        self.assertEqual(False, netmri.ssl_verify)

        netmri = InfobloxNetMRI(ssl_verify="no", **self.opts)
        self.assertEqual(False, netmri.ssl_verify)

        netmri = InfobloxNetMRI(ssl_verify="off", **self.opts)
        self.assertEqual(False, netmri.ssl_verify)

        netmri = InfobloxNetMRI(ssl_verify=False, **self.opts)
        self.assertEqual(False, netmri.ssl_verify)

        netmri = InfobloxNetMRI(ssl_verify="false", **self.opts)
        self.assertEqual(False, netmri.ssl_verify)

        netmri = InfobloxNetMRI(ssl_verify="true", **self.opts)
        self.assertEqual(True, netmri.ssl_verify)

        netmri = InfobloxNetMRI(ssl_verify='yes', **self.opts)
        self.assertEqual(True, netmri.ssl_verify)

        netmri = InfobloxNetMRI(ssl_verify='on', **self.opts)
        self.assertEqual(True, netmri.ssl_verify)

        netmri = InfobloxNetMRI(ssl_verify=True, **self.opts)
        self.assertEqual(True, netmri.ssl_verify)
Пример #7
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 ')
Пример #8
0
    def test_init_ssl_verify_file(self, mock_isfile):
        mock_isfile.return_value = True
        netmri = InfobloxNetMRI(ssl_verify='/some/path.crt', **self.opts)
        self.assertEqual('/some/path.crt', netmri.ssl_verify)

        mock_isfile.return_value = False
        self.assertRaises(ValueError,
                          InfobloxNetMRI,
                          ssl_verify='/some/path.crt',
                          **self.opts)
Пример #9
0
def get_api_client():
    global _client
    conf = get_config()
    if _client is None:
        _client = InfobloxNetMRI(conf.host,
                                 conf.username,
                                 conf.password,
                                 api_version=NETMRI_API_VERSION)

    return _client
Пример #10
0
    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()
Пример #11
0
def print_info(object):
    print(type(object))
    print(dir(object))


netmri_password = getpass.getpass("Enter the Password: "******"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:
Пример #12
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)
from infoblox_netmri.client import InfobloxNetMRI

parser = argparse.ArgumentParser(description='run jobs for specific devices')
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
Пример #14
0
parser = argparse.ArgumentParser(description='run jobs for specific devices')
parser.add_argument('script_name', help="script name")
parser.add_argument('pattern', help="name pattern")
parser.add_argument('command', help="value of the Script-Variable $command")
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
from infoblox_netmri.client import InfobloxNetMRI
import getpass

netmri_password = getpass.getpass("Enter the Password: "******"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):
Пример #16
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)
Пример #17
0
# to fetch the interface details of a devices
from infoblox_netmri.client import InfobloxNetMRI
from pprint import pprint
import time

defaults = {
    "host": "10.*.*.*",
    "username": "******",
    "password": "******",
}

infoblox_client = InfobloxNetMRI(
    defaults.get("host"),
    defaults.get("username"),
    defaults.get("password"),
    api_version="3.*.*",
)
x = 'aj-test-switch'
querystring = {
    'op_DeviceName': "=",
    'val_c_DeviceName': x,
    'methods': "interfaces",
    'select': "interfaces",
}
devicedetails = infoblox_client.api_request(
    'devices/find', querystring
)  # the interface details will be stored in devicedetails in multi-level dictionary
pprint(devicedetails['devices'])
Пример #18
0
 def test_package_creation(self):
     netmri = InfobloxNetMRI(**self.opts)
     package = "infoblox_netmri.api.broker.v3_0_0.device_broker.DeviceBroker"
     self.assertEquals(package, netmri._get_broker_package("Device"))
Пример #19
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))
Пример #20
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))
Пример #21
0
 def test_init_valid(self):
     netmri = InfobloxNetMRI(**self.opts)
     self.assertEqual(type(netmri), InfobloxNetMRI)