Example #1
0
def test_snmp_set_address(set_data):
    dev = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    try:
        dev.set('1', '1.1.1.1')
        success = True
    except:
        success = False

    assert success
Example #2
0
def test_arg_non_default_port():
    dev = SnmpHandler(host='1.1.1.1',
                      version='2c',
                      community='public',
                      port=35000)
    assert dev.version == '2c'
    assert dev.port == 35000
Example #3
0
def test_device_versions(declared_hostinfo):
    dev = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    hostinfo = HostInfo(dev)
    hostinfo.get_version()
    assert hostinfo.vendor == declared_hostinfo.vendor
    assert hostinfo.os == declared_hostinfo.os
    assert hostinfo.version == declared_hostinfo.version
def main():
    module = AnsibleModule(argument_spec=dict(
        host=dict(required=True),
        version=dict(required=True, choices=['2c', '3']),
        community=dict(required=False, default=False),
        username=dict(required=False),
        level=dict(required=False, choices=['authNoPriv', 'authPriv']),
        integrity=dict(required=False, choices=['md5', 'sha']),
        privacy=dict(required=False,
                     choices=['des', '3des', 'aes', 'aes192', 'aes256']),
        authkey=dict(required=False),
        privkey=dict(required=False),
        source=dict(required=True,
                    choices=['startup-config', 'running-config', 'tftp']),
        destination=dict(required=True,
                         choices=['startup-config', 'running-config', 'tftp']),
        server=dict(required=False, default=False),
        filename=dict(required=False, default=False),
        removeplaceholder=dict(required=False)),
                           required_together=(
                               ['username', 'level', 'integrity', 'authkey'],
                               ['privacy', 'privkey'],
                           ),
                           supports_check_mode=False)

    m_args = module.params

    if not has_nelsnmp:
        module.fail_json(msg='Missing required nelsnmp module (check docs)')

    # Verify that we receive a community when using snmp v2
    if m_args['version'] == "2c":
        if m_args['community'] == False:
            module.fail_json(msg='Community not set when using snmp version 2')

    if m_args['version'] == "3":
        if m_args['username'] == None:
            module.fail_json(msg='Username not set when using snmp version 3')

        if m_args['level'] == "authPriv" and m_args['privacy'] == None:
            module.fail_json(
                msg='Privacy algorithm not set when using authPriv')

    if m_args['source'] == "tftp" or m_args['destination'] == "tftp":
        if not m_args['server'] or not m_args['filename']:
            module.fail_json(
                msg=
                'server and filename are required when source or destination is tftp'
            )

    nelsnmp_args = {}
    for key in m_args:
        if key in NELSNMP_PARAMETERS and m_args[key] != None:
            nelsnmp_args[key] = m_args[key]

    try:
        dev = SnmpHandler(**nelsnmp_args)
    except Exception, err:
        module.fail_json(msg=str(err))
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(required=True),
            version=dict(required=True, choices=['2c', '3']),
            community=dict(required=False, default=False),
            username=dict(required=False),
            level=dict(required=False, choices=['authNoPriv', 'authPriv']),
            integrity=dict(required=False, choices=['md5', 'sha']),
            privacy=dict(required=False,
                         choices=['des', '3des', 'aes', 'aes192', 'aes256']),
            authkey=dict(required=False),
            privkey=dict(required=False),
            mode=dict(required=True,
                      choices=[
                          'access', 'trunk', 'desireable', 'auto',
                          'trunk-nonegotiate'
                      ]),
            interface_id=dict(required=False),
            interface_name=dict(required=False),
            access_vlan=dict(required=False),
            native_vlan=dict(required=False),
            removeplaceholder=dict(required=False),
        ),
        mutually_exclusive=(['interface_id', 'interface_name'], ),
        required_one_of=(['interface_id', 'interface_name'], ),
        required_together=(
            ['username', 'level', 'integrity', 'authkey'],
            ['privacy', 'privkey'],
        ),
        supports_check_mode=False)

    m_args = module.params

    if not has_nelsnmp:
        module.fail_json(msg='Missing required nelsnmp module (check docs)')

    # Verify that we receive a community when using snmp v2
    if m_args['version'] == "2c":
        if m_args['community'] == False:
            module.fail_json(msg='Community not set when using snmp version 2')

    if m_args['version'] == "3":
        if m_args['username'] == None:
            module.fail_json(msg='Username not set when using snmp version 3')

        if m_args['level'] == "authPriv" and m_args['privacy'] == None:
            module.fail_json(
                msg='Privacy algorithm not set when using authPriv')

    nelsnmp_args = {}
    for key in m_args:
        if key in NELSNMP_PARAMETERS and m_args[key] != None:
            nelsnmp_args[key] = m_args[key]

    try:
        dev = SnmpHandler(**nelsnmp_args)
    except Exception, err:
        module.fail_json(msg=str(err))
Example #6
0
def test_hostinfo_cisco_ios_version():
    handler = SnmpHandler(host='1.1.1.1')
    hostinfo = HostInfo(
        handler,
        vendor='cisco',
        description='Cisco IOS Software, catalyst, Version 15.x, RELEASE')
    hostinfo.get_version()
    assert hostinfo.version == '15.x'
Example #7
0
def test_arg_timeout_and_retries():
    dev = SnmpHandler(host='1.1.1.1',
                      version='2c',
                      community='public',
                      timeout=4,
                      retries=10)
    assert dev.timeout == 4
    assert dev.retries == 10
Example #8
0
def test_arg_timeout_and_retries_defaults():
    dev = SnmpHandler(
        host='1.1.1.1',
        version='2c',
        community='public',
    )
    assert dev.timeout == 1
    assert dev.retries == 5
Example #9
0
def test_hostinfo_pysnmp_netsnmp(patch_pysnmp_getnext):
    handler = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    hostinfo = HostInfo(
        handler,
        vendor='net-snmp',
        description='Cisco IOS Software, catalyst, Version 15.x, RELEASE')
    hostinfo.get_version()
    assert hostinfo.version == 'UNKNOWN'
Example #10
0
def test_snmp_handler_v3_authnopriv():
    dev = SnmpHandler(host='1.1.1.1',
                      version='3',
                      username='******',
                      level='authNoPriv',
                      integrity='sha',
                      authkey='authpass')
    assert dev.version == '3'
    assert dev.authkey == 'authpass'
Example #11
0
def test_snmp_handler_missing_version():
    with pytest.raises(ArgumentError):
        SnmpHandler(host='1.1.1.1',
                    username='******',
                    level='authPriv',
                    integrity='sha',
                    privacy='aes',
                    authkey='authpass',
                    privkey='privkey')
Example #12
0
def test_hostinfo_get_all(declared_hostinfo):
    dev = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    hostinfo = HostInfo(dev)
    hostinfo.get_all()
    assert hostinfo.description == 'Cisco Adaptive Security Appliance Version 9.3(2)2'
    assert hostinfo.contact == 'Networklore'
    assert hostinfo.location == 'Westeros'
    assert hostinfo.vendor == 'cisco'
    assert hostinfo.version == '9.3(2)2'
Example #13
0
def test_snmpv3_arg_missing_level():
    with pytest.raises(ArgumentError):
        SnmpHandler(host='1.1.1.1',
                    version='3',
                    username='******',
                    integrity='sha',
                    privacy='aes',
                    authkey='authpass',
                    privkey='privkey')
Example #14
0
def test_snmp_handler_v3_authpriv():
    dev = SnmpHandler(host='1.1.1.1',
                      version='3',
                      username='******',
                      level='authPriv',
                      integrity='sha',
                      privacy='aes',
                      authkey='authpass',
                      privkey='privkey')
    assert dev.version == '3'
Example #15
0
def test_snmp_arg_missing_privacy():
    with pytest.raises(ArgumentError):
        SnmpHandler(host='1.1.1.1',
                    version='3',
                    username='******',
                    level='authPriv',
                    integrity='sha',
                    authkey='authpass',
                    privkey='privkey',
                    port=65532)
Example #16
0
def test_snmp_arg_invalid_port_type():
    with pytest.raises(ArgumentError):
        SnmpHandler(host='1.1.1.1',
                    version='3',
                    username='******',
                    level='authPriv',
                    integrity='sha',
                    privacy='aes',
                    authkey='authpass',
                    privkey='privkey',
                    port='five')
Example #17
0
def test_handle_snmp_handler_invalid_version():
    try:
        dev = SnmpHandler(host='1.1.1.1',
                          version='4',
                          username='******',
                          level='authPriv',
                          integrity='sha',
                          privacy='aes',
                          authkey='authpass',
                          privkey='privkey')
    except ArgumentError as e:
        assert e.__str__() == "No valid SNMP version defined"
Example #18
0
    def _get_device_os(self, ip):
        dev = SnmpHandler(host=ip,
                          version=self.snmp_version,
                          community=self.snmp_community)
        hostinfo = HostInfo(dev)

        try:
            hostinfo.get_version()
            self.logger.info(f'{ip}: detected os "{hostinfo.os}"')
        except SnmpError as e:
            self.logger.error(f'{ip}: snmp-timeout')
            return False

        return hostinfo.os
Example #19
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(required=True),
            version=dict(required=True, choices=['2c', '3']),
            community=dict(required=False, default=False),
            username=dict(required=False),
            level=dict(required=False, choices=['authNoPriv', 'authPriv']),
            integrity=dict(required=False, choices=['md5', 'sha']),
            port=dict(required=False, default=161, type='int'),
            privacy=dict(required=False, choices=[
                'des', '3des', 'aes', 'aes192', 'aes256']),
            authkey=dict(required=False),
            privkey=dict(required=False),
            oid=dict(required=True, type='list'),
            query_type=dict(choices=['get', 'getnext'], default='get')),
        required_together=(
            ['username', 'level', 'integrity', 'authkey'],
            ['privacy', 'privkey']
        ),
        supports_check_mode=False)

    m_args = module.params

    if not has_nelsnmp:
        module.fail_json(msg='Missing required nelsnmp module (check docs)')

    # Verify that we receive a community when using snmp v2
    if m_args['version'] == "2c":
        if m_args['community'] is False:
            module.fail_json(msg='Community not set when using snmp version 2')

    if m_args['version'] == "3":
        if m_args['username'] is None:
            module.fail_json(msg='Username not set when using snmp version 3')

        if m_args['level'] == "authPriv" and m_args['privacy'] is None:
            module.fail_json(msg='Privacy algorithm not set when using authPriv')

    nelsnmp_args = {}
    for key in m_args:
        if key in NELSNMP_PARAMETERS and m_args[key] is not None:
            nelsnmp_args[key] = m_args[key]

    try:
        dev = SnmpHandler(**nelsnmp_args)
    except Exception, err:
        module.fail_json(msg=str(err))
Example #20
0
    def _get_device_os(self, ip):
        dev = SnmpHandler(host=ip, version=self.snmp_version, community=self.snmp_community)
        hostinfo = HostInfo(dev)

        try:
            hostinfo.get_version()
            self.logger.info(f'{ip}: detected os "{hostinfo.os}"')
        except SnmpError:
            self.logger.error(f'{ip}: snmp-timeout')
            return False

        if self.network_driver != '':
            self.logger.info(f'{ip}: custom configs overwrites os to: "{self.network_driver}"')
            return self.network_driver

        return hostinfo.os
Example #21
0
def test_hostinfo_get_vendor(sysobject):
    handler = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    hostinfo = HostInfo(handler)
    hostinfo.get_vendor()
    assert hostinfo.vendor == 'cisco'
Example #22
0
def test_snmp_missing_host():
    with pytest.raises(ArgumentError):
        SnmpHandler(version='2c', community='public')
Example #23
0
def test_hostinfo_get_vendor_unknown(declared_hostinfo_unknown_vendor):
    dev = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    hostinfo = HostInfo(dev)
    hostinfo.get_vendor()
    assert hostinfo.vendor == 'UNKNOWN'
def test_return_value_types(query_data):
    dev = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    varbinds = dev.get('1')
    for oid, value in varbinds:
        assert value == query_data.value
Example #25
0
def test_hostinfo_get_version_known_vendor(declared_hostinfo):
    dev = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    hostinfo = HostInfo(dev, vendor='cisco')
    hostinfo.get_version()
    assert hostinfo.version == '9.3(2)2'
Example #26
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(required=True),
            version=dict(required=True, choices=['2c', '3']),
            community=dict(required=False, default=False),
            username=dict(required=False),
            level=dict(required=False, choices=['authNoPriv', 'authPriv']),
            integrity=dict(required=False, choices=['md5', 'sha']),
            privacy=dict(required=False, choices=['des', '3des', 'aes', 'aes192', 'aes256']),
            authkey=dict(required=False),
            privkey=dict(required=False),
            interface_id=dict(required=False),
            interface_name=dict(required=False),
            portsecurity=dict(required=False, choices=['enabled', 'disabled']),
            max=dict(required=False),
            sticky=dict(required=False, choices=['enabled', 'disabled']),
            violation=dict(required=False, choices=['shutdown', 'restrict', 'protect']),
            aging_type=dict(required=False, choices=['absolute', 'inactivity']),
            aging_time=dict(required=False),
            aging_static=dict(required=False, choices=['enabled', 'disabled']),
            removeplaceholder=dict(required=False),
        ),
        mutually_exclusive=(['interface_id', 'interface_name'],),
        required_one_of=(
            ['interface_id', 'interface_name'],
            ['portsecurity', 'max', 'sticky', 'violation', 'aging_type','aging_time'],
        ),
        required_together=(
            ['username','level','integrity','authkey'],['privacy','privkey'],
        ),
        supports_check_mode=False)

    m_args = module.params

    if not has_nelsnmp:
        module.fail_json(msg='Missing required nelsnmp module (check docs)')

    # Verify that we receive a community when using snmp v2
    if m_args['version'] == "2c":
        if m_args['community'] == False:
            module.fail_json(msg='Community not set when using snmp version 2')

    if m_args['version'] == "3":
        if m_args['username'] == None:
            module.fail_json(msg='Username not set when using snmp version 3')

        if m_args['level'] == "authPriv" and m_args['privacy'] == None:
            module.fail_json(msg='Privacy algorithm not set when using authPriv')

    nelsnmp_args = {}
    for key in m_args:
        if key in NELSNMP_PARAMETERS and m_args[key] != None:
            nelsnmp_args[key] = m_args[key]

    try:
        dev = SnmpHandler(**nelsnmp_args)
    except Exception as err:
        module.fail_json(msg=str(err))

    has_changed = False

    if m_args['interface_name']:
        # Do this through cache in the future
        try:
            interface = False
            vartable = dev.getnext(o.ifDescr)

            for varbinds in vartable:
                for oid, val in varbinds:
                    if m_args['interface_name'] == val:
                        interface = oid.rsplit('.', 1)[-1]

            if interface == False:
                module.fail_json(msg='Unable to find interface')
        except Exception as err:
            module.fail_json(msg=str(err))

    # Check how to get the interface value
    if m_args['interface_id']:
        interface = m_args['interface_id']

    if m_args['portsecurity']:
        oid = o.cpsIfPortSecurityEnable + "." + str(interface)
        desired_state = TRUTHVALUE[m_args['portsecurity']]
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    if m_args['max']:
        oid = o.cpsIfMaxSecureMacAddr + "." + str(interface)
        desired_state = int(m_args['max'])
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    if m_args['sticky']:
        oid = o.cpsIfStickyEnable + "." + str(interface)
        desired_state = TRUTHVALUE[m_args['sticky']]
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    if m_args['violation']:
        oid = o.cpsIfViolationAction + "." + str(interface)
        desired_state = VIOLATION[m_args['violation']]
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    if m_args['aging_type']:
        oid = o.cpsIfSecureMacAddrAgingType + "." + str(interface)
        desired_state = AGING_TYPE[m_args['aging_type']]
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    if m_args['aging_time']:
        oid = o.cpsIfSecureMacAddrAgingTime + "." + str(interface)
        desired_state = int(m_args['aging_time'])
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    if m_args['aging_static']:
        oid = o.cpsIfStaticMacAddrAgingEnable + "." + str(interface)
        desired_state = TRUTHVALUE[m_args['aging_static']]
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    return_status = { 'changed': has_changed }

    module.exit_json(**return_status)
Example #27
0
def test_hostinfo_pysnmp_get(patch_pysnmp_get, snmp_val):
    handler = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    data = handler.get_value('1.1')
    assert data == snmp_val
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(required=True),
            version=dict(required=True, choices=['2c', '3']),
            community=dict(required=False, default=False),
            username=dict(required=False),
            level=dict(required=False, choices=['authNoPriv', 'authPriv']),
            integrity=dict(required=False, choices=['md5', 'sha']),
            privacy=dict(required=False,
                         choices=['des', '3des', 'aes', 'aes192', 'aes256']),
            authkey=dict(required=False),
            privkey=dict(required=False),
            mode=dict(required=True,
                      choices=[
                          'access', 'trunk', 'desireable', 'auto',
                          'trunk-nonegotiate'
                      ]),
            interface_id=dict(required=False),
            interface_name=dict(required=False),
            access_vlan=dict(required=False),
            native_vlan=dict(required=False),
            removeplaceholder=dict(required=False),
        ),
        mutually_exclusive=(['interface_id', 'interface_name'], ),
        required_one_of=(['interface_id', 'interface_name'], ),
        required_together=(
            ['username', 'level', 'integrity', 'authkey'],
            ['privacy', 'privkey'],
        ),
        supports_check_mode=False)

    m_args = module.params

    if not has_nelsnmp:
        module.fail_json(msg='Missing required nelsnmp module (check docs)')

    # Verify that we receive a community when using snmp v2
    if m_args['version'] == "2c":
        if m_args['community'] == False:
            module.fail_json(msg='Community not set when using snmp version 2')

    if m_args['version'] == "3":
        if m_args['username'] == None:
            module.fail_json(msg='Username not set when using snmp version 3')

        if m_args['level'] == "authPriv" and m_args['privacy'] == None:
            module.fail_json(
                msg='Privacy algorithm not set when using authPriv')

    nelsnmp_args = {}
    for key in m_args:
        if key in NELSNMP_PARAMETERS and m_args[key] != None:
            nelsnmp_args[key] = m_args[key]

    try:
        dev = SnmpHandler(**nelsnmp_args)
    except Exception as err:
        module.fail_json(msg=str(err))

    #return_status = { 'changed': False }
    has_changed = False

    if m_args['interface_name']:
        # Do this through cache in the future
        try:
            interface = False
            vartable = dev.getnext(o.ifDescr)

            for varbinds in vartable:
                for oid, val in varbinds:
                    if m_args['interface_name'] == val:
                        interface = oid.rsplit('.', 1)[-1]

            if interface == False:
                module.fail_json(msg='Unable to find interface')
        except Exception as err:
            module.fail_json(msg=str(err))

    # Check how to get the interface value
    if m_args['interface_id']:
        interface = m_args['interface_id']

    if m_args['mode']:
        oid = o.vlanTrunkPortDynamicState + "." + str(interface)
        desired_state = PORT_MODE[m_args['mode']]
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    if m_args['access_vlan']:
        oid = o.vmVlan + "." + str(interface)
        desired_state = int(m_args['access_vlan'])
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    if m_args['native_vlan']:
        oid = o.vlanTrunkPortNativeVlan + "." + str(interface)
        desired_state = int(m_args['native_vlan'])
        changed = set_state(dev, oid, desired_state, module)
        has_changed = changed_status(changed, has_changed)

    return_status = {'changed': has_changed}

    module.exit_json(**return_status)
Example #29
0
def test_snmp_handler_v2c():
    dev = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    assert dev.version == '2c'
    assert dev.port == 161
Example #30
0
def test_hostinfo():
    handler = SnmpHandler(host='1.1.1.1')
    hostinfo = HostInfo(handler)
    assert hostinfo.os is None
Example #31
0
def test_fixturet(doesitwork):
    handler = SnmpHandler(host='1.1.1.1', version='2c', community='public')
    data = handler.get_value('1.1')
    assert data == '1.1'