コード例 #1
0
 def testCommandoResultsBad(self):
     commands = ["show run | in cisco"]
     commando = Commando(devices=[self.device.nodeName])
     data = commando.parse_template(results=[no_template_data],
                                    device=self.device,
                                    commands=commands)
     self.assertTrue(len(data) > 0)
     self.assertTrue(isinstance(data, list))
     self.assertTrue(isinstance(data[0], str))
     self.assertEquals(commando.parsed_results, {})
コード例 #2
0
 def testCommandoResultsGood(self):
     commands = ["show version"]
     commando = Commando(devices=[self.device.nodeName])
     data = commando.parse_template(results=[big_cli_data],
                                    device=self.device,
                                    commands=commands)
     self.assertTrue(len(data) > 0)
     self.assertTrue(isinstance(data, list))
     self.assertTrue(isinstance(data[0], str))
     self.assertTrue(isinstance(commando.parsed_results, dict))
     self.assertEquals(
         commando.parsed_results.popitem()[1]["show version"]["hardware"],
         ['CSR1000V'])
コード例 #3
0
def main():

    module = AnsibleModule(
        argument_spec=dict(
            connection=dict(choices=['ssh', 'offline', 'netmiko_ssh',
                            'trigger_ssh', 'netmiko_telnet', 'telnet'], default='netmiko_ssh'),
            platform=dict(required=False),
            file=dict(required=False),
            local_file=dict(required=False),
            index_file=dict(default='index'),
            template_dir=dict(default='ntc-templates/templates'),
            use_templates=dict(required=False, default=True, type='bool'),
            trigger_device_list=dict(type='list', required=False),
            command=dict(required=True),
            host=dict(required=False),
            provider=dict(required=False, type='dict'),
            port=dict(required=False),
            delay=dict(default=1, required=False),
            global_delay_factor=dict(default=1, required=False),
            username=dict(required=False, type='str'),
            password=dict(required=False, type='str', no_log=True),
            secret=dict(required=False, type='str', no_log=True),
            use_keys=dict(required=False, default=False, type='bool'),
            key_file=dict(required=False, default=None),
            optional_args=dict(required=False, type='dict', default={}),
        ),
        mutually_exclusive=(
            ['host', 'trigger_device_list'],
        ),
        supports_check_mode=False
    )

    provider = module.params['provider'] or {}

    no_log = ['password', 'secret']
    for param in no_log:
        if provider.get(param):
            module.no_log_values.update(return_values(provider[param]))

    # allow local params to override provider
    for param, pvalue in provider.items():
        if module.params.get(param) != False:
            module.params[param] = module.params.get(param) or pvalue

    if not HAS_TEXTFSM:
        module.fail_json(msg='This module requires TextFSM')

    connection = module.params['connection']
    platform = module.params['platform']
    device_type = platform.split('-')[0]
    raw_file = module.params['file']
    local_file = module.params['local_file']
    index_file = module.params['index_file']
    template_dir = module.params['template_dir']
    command = module.params['command']
    username = module.params['username']
    password = module.params['password']
    secret = module.params['secret']
    use_templates = module.params['use_templates']
    use_keys = module.params['use_keys']
    key_file = module.params['key_file']
    delay = int(module.params['delay'])
    global_delay_factor = int(module.params['global_delay_factor'])
    trigger_device_list = module.params['trigger_device_list']
    optional_args = module.params['optional_args']
    host = module.params['host']

    if (connection in ['ssh', 'netmiko_ssh', 'netmiko_telnet', 'telnet'] and
            not module.params['host']):
        module.fail_json(msg='specify host when connection='
                             'ssh/netmiko_ssh/netmiko_telnet')

    if connection in ['netmiko_telnet', 'telnet'] and platform != 'cisco_ios':
        module.fail_json(msg='only cisco_ios supports '
                             'telnet/netmiko_telnet connection')

    if platform == 'cisco_ios' and connection in ['netmiko_telnet', 'telnet']:
        device_type = 'cisco_ios_telnet'

    if module.params['port']:
        port = int(module.params['port'])
    else:
        if device_type == 'cisco_ios_telnet':
            port = 23
        else:
            port = 22

    argument_check = { 'platform': platform }
    if connection != 'offline':
        argument_check['username'] = username
        argument_check['password'] = password
        argument_check['host'] = host
        if not host and not trigger_device_list:
            module.fail_json(msg='specify host or trigger_device_list based on connection')

    for key, val in argument_check.items():
        if val is None:
            module.fail_json(msg=str(key) + " is required")

    if connection == 'offline' and not raw_file:
        module.fail_json(msg='specifiy file if using connection=offline')

    if template_dir.endswith('/'):
        template_dir.rstrip('/')

    if use_templates:
        if not os.path.isfile(template_dir + '/' + index_file):
            module.fail_json(msg='could not find or read index file')

        if raw_file and not os.path.isfile(raw_file):
            module.fail_json(msg='could not read raw text file')


    rawtxt = ''
    if connection in ['ssh', 'netmiko_ssh', 'netmiko_telnet', 'telnet']:
        if not HAS_NETMIKO:
            module.fail_json(msg='This module requires netmiko.')

        device = ConnectHandler(
            device_type=device_type,
            ip=host,
            port=port,
            username=username,
            password=password,
            secret=secret,
            use_keys=use_keys,
            key_file=key_file,
            global_delay_factor=global_delay_factor
        )
        if secret:
            device.enable()

        rawtxt = device.send_command_timing(command, delay_factor=delay)

    elif connection == 'trigger_ssh':
        if not HAS_TRIGGER:
            module.fail_json(msg='This module requires trigger.')
        kwargs = {}
        kwargs['production_only'] = False
        kwargs['force_cli'] = True
        if optional_args:
            kwargs.update(optional_args)

        if host:
            commando = Commando(devices=[host], commands=[command],
                                creds=(username, password), **kwargs)
            commando.run()
            rawtxt = commando.results[host][command]
        elif trigger_device_list:
            commando = Commando(devices=trigger_device_list, commands=[command],
                                creds=(username, password), **kwargs)
            commando.run()

    elif connection == 'offline':
        with open(raw_file, 'r') as data:
            rawtxt = data.read()

    if local_file:
        with open(local_file, 'w') as f:
            f.write(rawtxt)

    results = {}
    results['response'] = []
    results['response_list'] = []

    if use_templates:
        if rawtxt:
            results['response'] = parse_raw_output(rawtxt, module)
        elif trigger_device_list:
            results['response_list'] = parse_raw_output(commando.results, module)
    elif rawtxt:
        results['response'] = [rawtxt]
    elif trigger_device_list:
        results['response'] = [commando.results]

    module.exit_json(**results)
コード例 #4
0
#!/Users/rlaney/.virtualenvs/NetEngineerONE/bin/python

#Importing the necessary module.
from trigger.cmds import Commando

#Asking the user for input.
devices = raw_input('\nEnter devices separated by comma: ')
commands = raw_input('\nEnter commands separated by comma: ')

#Splitting the devices/commands entered by the user.
devices_list = devices.split(',')
commands_list = commands.split(',')

#Running all given commands on all given devices.
cmd = Commando(devices=devices_list, commands=commands_list)

#Executing all the work in real time.
cmd.run()

#Capturing the results as a dictionary of dictionaries.
#Uncomment 'print result', then save and run the script...
#...to see how Commando returns the results initially.
output = cmd.results
#print output

#Using a while loop to allow the user to return and choose another cXdY combination.
while True:
    #Asking the user about the output he wants to obtain.
    print '\nNOTE! The format is always cXdY, where X is the command number and Y is the device number in the lists you enter.\nIf X = a this means that command Y will be executed on ALL devices.\nIf Y = a this means that all commands will be executed on device X.\nIf both X = a and Y = a then all the commands will be executed on all devices.'

    user_option_1 = raw_input(
コード例 #5
0
#Importing the necessary module.
from trigger.cmds import Commando

#Asking the user for input.
devices = raw_input('\nEnter devices separated by comma: ')
commands = raw_input('\nEnter commands separated by comma: ')

#Splitting the devices/commands entered by the user.
devices_list = devices.split(',')
commands_list = commands.split(',')

#Running all given commands on all given devices. 
cmd = Commando(devices = devices_list, commands = commands_list, force_cli = True, creds = ('mihai1', 'python1', 'juniper'))

#Executing all the work in real time.
cmd.run()

#Capturing the results as a dictionary of dictionaries.
#Uncomment 'print result', then save and run the script...
#...to see how Commando returns the results initially.
output = cmd.results
#print output

#Using a while loop to allow the user to return and choose another cXdY combination.
while True:
	#Asking the user about the output he wants to obtain.
	print '\nNOTE! The format is always cXdY, where X is the command number and Y is the device number in the lists you enter.\nIf X = a this means that command Y will be executed on ALL devices.\nIf Y = a this means that all commands will be executed on device X.\nIf both X = a and Y = a then all the commands will be executed on all devices.'
	
	user_option_1 = raw_input('\nNow, what do you want to see? Example: To get the output of command 2 on device 1 just type c2d1: ')

	#Identifying the desired command(s) and device(s), based on the user input above.
コード例 #6
0
def main():

    module = AnsibleModule(argument_spec=dict(
        connection=dict(
            choices=['ssh', 'offline', 'netmiko_ssh', 'trigger_ssh'],
            default='netmiko_ssh'),
        platform=dict(required=True),
        file=dict(required=False),
        local_file=dict(required=False),
        index_file=dict(default='index'),
        template_dir=dict(default='ntc-templates/templates'),
        use_templates=dict(required=False, default=True, type='bool'),
        trigger_device_list=dict(type='list', required=False),
        command=dict(required=True),
        host=dict(required=False),
        port=dict(default=22, required=False),
        delay=dict(default=1, required=False),
        username=dict(required=False, type='str'),
        password=dict(required=False, type='str'),
        secret=dict(required=False, type='str'),
        use_keys=dict(required=False, default=False, type='bool'),
        key_file=dict(required=False, default=None),
        optional_args=dict(required=False, type='dict', default={}),
    ),
                           required_together=(['password', 'username'], ),
                           mutually_exclusive=(['host',
                                                'trigger_device_list'], ),
                           supports_check_mode=False)

    if not HAS_TEXTFSM:
        module.fail_json(msg='This module requires TextFSM')

    connection = module.params['connection']
    platform = module.params['platform']
    device_type = platform.split('-')[0]
    raw_file = module.params['file']
    local_file = module.params['local_file']
    index_file = module.params['index_file']
    template_dir = module.params['template_dir']
    command = module.params['command']
    username = module.params['username']
    password = module.params['password']
    secret = module.params['secret']
    use_templates = module.params['use_templates']
    use_keys = module.params['use_keys']
    key_file = module.params['key_file']
    port = int(module.params['port'])
    delay = int(module.params['delay'])
    trigger_device_list = module.params['trigger_device_list']
    optional_args = module.params['optional_args']
    host = module.params['host']

    if connection in ['ssh', 'netmiko_ssh'] and not module.params['host']:
        module.fail_json(msg='specify host when connection=ssh/netmiko_ssh')

    if connection != 'offline':
        if not host and not trigger_device_list:
            module.fail_json(
                msg='specify host or trigger_device_list based on connection')

    if connection == 'offline' and not raw_file:
        module.fail_json(msg='specifiy file if using connection=offline')

    if template_dir.endswith('/'):
        template_dir.rstrip('/')

    if use_templates:
        if not os.path.isfile(template_dir + '/' + index_file):
            module.fail_json(msg='could not find or read index file')

        if raw_file and not os.path.isfile(raw_file):
            module.fail_json(msg='could not read raw text file')

    rawtxt = ''
    if connection in ['ssh', 'netmiko_ssh']:
        if not HAS_NETMIKO:
            module.fail_json(msg='This module requires netmiko.')

        device = ConnectHandler(device_type=device_type,
                                ip=host,
                                port=port,
                                username=username,
                                password=password,
                                secret=secret,
                                use_keys=use_keys,
                                key_file=key_file)
        if secret:
            device.enable()

        rawtxt = device.send_command_expect(command, delay_factor=delay)

    elif connection == 'trigger_ssh':
        if not HAS_TRIGGER:
            module.fail_json(msg='This module requires trigger.')
        kwargs = {}
        kwargs['production_only'] = False
        kwargs['force_cli'] = True
        if optional_args:
            kwargs.update(optional_args)

        if host:
            commando = Commando(devices=[host],
                                commands=[command],
                                creds=(username, password),
                                **kwargs)
            commando.run()
            rawtxt = commando.results[host][command]
        elif trigger_device_list:
            commando = Commando(devices=trigger_device_list,
                                commands=[command],
                                creds=(username, password),
                                **kwargs)
            commando.run()

    elif connection == 'offline':
        with open(raw_file, 'r') as data:
            rawtxt = data.read()

    if local_file:
        with open(local_file, 'w') as f:
            f.write(rawtxt)

    results = {}
    results['response'] = []
    results['response_list'] = []

    if use_templates:
        if rawtxt:
            results['response'] = parse_raw_output(rawtxt, module)
        elif trigger_device_list:
            results['response_list'] = parse_raw_output(
                commando.results, module)
    elif rawtxt:
        results['response'] = [rawtxt]
    elif trigger_device_list:
        results['response'] = [commando.results]

    module.exit_json(**results)