Advertisement
Guest User

Untitled

a guest
Jan 15th, 2019
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.83 KB | None | 0 0
  1. (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ ansible-playbook --version
  2. ansible-playbook 2.7.5
  3.   config file = None
  4.   configured module search path = [u'/Users/dcc/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  5.   ansible python module location = /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible
  6.   executable location = /Users/dcc/venvs/ansible-latest/bin/ansible-playbook
  7.   python version = 2.7.10 (default, Feb  7 2017, 00:08:15) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)]
  8.  
  9. (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$  cat dev_inentory.txt
  10. [em316]
  11. MR-EM316LNXNM-I-1-LAP01-US
  12. MR-EM316LNXNM-I-1-LDP07-GB
  13.  
  14. [em316:vars]
  15. ansible_ssh_user=admin
  16. ansible_ssh_pass=xxxxxxxxxxxxx
  17. ansible_network_os=EM316LNXNM
  18.  
  19. (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat agnostic.yml
  20. ---
  21. - name: AGNOSTIC PLAYBOOK
  22.   hosts: em316
  23.   gather_facts: false
  24.   connection: network_cli
  25.  
  26.   tasks:
  27.      - name: Set remote server
  28.        cli_config:
  29.          config: aaa remote-server host 1 10.64.21.16 SECRET
  30.  
  31.  
  32. (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ ansible-playbook -i dev_inentory.txt agnostic.yml
  33.  
  34. PLAY [AGNOSTIC PLAYBOOK] *********************************************************************************************************************************************************************************************************************************
  35.  
  36. TASK [Set remote server] *********************************************************************************************************************************************************************************************************************************
  37. ok: [MR-EM316LNXNM-I-1-LAP01-US]
  38. ok: [MR-EM316LNXNM-I-1-LDP07-GB]
  39.  
  40. PLAY RECAP ***********************************************************************************************************************************************************************************************************************************************
  41. MR-EM316LNXNM-I-1-LAP01-US : ok=1    changed=0    unreachable=0    failed=0
  42. MR-EM316LNXNM-I-1-LDP07-GB : ok=1    changed=0    unreachable=0    failed=0
  43.  
  44.  
  45. (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible/plugins/terminal/EM316LNXNM.py
  46. from __future__ import (absolute_import, division, print_function)
  47. __metaclass__ = type
  48.  
  49. import json
  50. import re
  51.  
  52. from ansible.errors import AnsibleConnectionFailure
  53. from ansible.module_utils._text import to_text, to_bytes
  54. from ansible.plugins.terminal import TerminalBase
  55. from ansible.utils.display import Display
  56.  
  57. display = Display()
  58.  
  59.  
  60. class TerminalModule(TerminalBase):
  61.  
  62.     terminal_stdout_re = [
  63.         re.compile(br"[\r\n]?[\w\+\-\.:\/\[\]]+(?:\([^\)]+\)){0,3}(?:[>#]) ?$")
  64.     ]
  65.  
  66.     terminal_stderr_re = [
  67.         re.compile(br"% ?Error"),
  68.         # re.compile(br"^% \w+", re.M),
  69.         re.compile(br"% ?Bad secret"),
  70.         re.compile(br"[\r\n%] Bad passwords"),
  71.         re.compile(br"invalid input", re.I),
  72.         re.compile(br"(?:incomplete|ambiguous) command", re.I),
  73.         re.compile(br"connection timed out", re.I),
  74.         re.compile(br"[^\r\n]+ not found"),
  75.         re.compile(br"'[^']' +returned error code: ?\d+"),
  76.         re.compile(br"Bad mask", re.I),
  77.         re.compile(br"% ?(\S+) ?overlaps with ?(\S+)", re.I),
  78.         re.compile(br"[%\S] ?Error: ?[\s]+", re.I),
  79.         re.compile(br"[%\S] ?Informational: ?[\s]+", re.I),
  80.         re.compile(br"Command authorization failed")
  81.     ]
  82.  
  83.     def on_open_shell(self):
  84.         try:
  85.             self._exec_cli_command(b'terminal length 0')
  86.         except AnsibleConnectionFailure:
  87.             raise AnsibleConnectionFailure('unable to set terminal parameters')
  88.  
  89.         try:
  90.             self._exec_cli_command(b'terminal width 512')
  91.         except AnsibleConnectionFailure:
  92.             display.display('WARNING: Unable to set terminal width, command responses may be truncated')
  93.  
  94.     def on_become(self, passwd=None):
  95.         if self._get_prompt().endswith(b'#'):
  96.             return
  97.  
  98.     def on_unbecome(self):
  99.         prompt = self._get_prompt()
  100.         if prompt is None:
  101.             # if prompt is None most likely the terminal is hung up at a prompt
  102.             return
  103.  
  104.         if b'(config' in prompt:
  105.             self._exec_cli_command(b'end')
  106.  
  107.  
  108. (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible/plugins/cliconf/EM316LNXNM.py
  109. from __future__ import (absolute_import, division, print_function)
  110. __metaclass__ = type
  111.  
  112. import re
  113. import json
  114.  
  115. from itertools import chain
  116.  
  117. from ansible.module_utils._text import to_text
  118. from ansible.module_utils.network.common.utils import to_list
  119. from ansible.plugins.cliconf import CliconfBase
  120.  
  121.  
  122. class Cliconf(CliconfBase):
  123.  
  124.     def get_device_info(self):
  125.         device_info = {}
  126.  
  127.         device_info['network_os'] = 'EM316LNXNM'
  128.         reply = self.get('show version')
  129.         data = to_text(reply, errors='surrogate_or_strict').strip()
  130.  
  131.         match = re.search(r'EM316LNXNM\s(v\S+\s\S+\s\S+)', data)
  132.         if match:
  133.             device_info['network_os_version'] = match.group(1)
  134.  
  135.         device_info['network_os_model'] = 'EM316LNXNM'
  136.  
  137.         return device_info
  138.  
  139.     def get_config(self, source='running', format='text', flags=None):
  140.         return self.send_command('show running-config')
  141.  
  142.     def edit_config(self, candidate=None, commit=True, replace=None, comment=None):
  143.         resp = {}
  144.         operations = self.get_device_operations()
  145.         self.check_edit_config_capability(operations, candidate, commit, replace, comment)
  146.  
  147.         results = []
  148.         requests = []
  149.         if commit:
  150.             self.send_command('configure terminal')
  151.             for line in to_list(candidate):
  152.                 if not isinstance(line, Mapping):
  153.                     line = {'command': line}
  154.  
  155.                 cmd = line['command']
  156.                 if cmd != 'end' and cmd[0] != '!':
  157.                     results.append(self.send_command(**line))
  158.                     requests.append(cmd)
  159.  
  160.             self.send_command('end')
  161.         else:
  162.             raise ValueError('check mode is not supported')
  163.  
  164.         resp['request'] = requests
  165.         resp['response'] = results
  166.         return resp
  167.  
  168.     def edit_macro(self, candidate=None, commit=True, replace=None, comment=None):
  169.         resp = {}
  170.         operations = self.get_device_operations()
  171.         self.check_edit_config_capabiltiy(operations, candidate, commit, replace, comment)
  172.  
  173.         results = []
  174.         requests = []
  175.         if commit:
  176.             commands = ''
  177.             for line in candidate:
  178.                 if line != 'None':
  179.                     commands += (' ' + line + '\n')
  180.                 self.send_command('config terminal', sendonly=True)
  181.                 obj = {'command': commands, 'sendonly': True}
  182.                 results.append(self.send_command(**obj))
  183.                 requests.append(commands)
  184.  
  185.             self.send_command('end', sendonly=True)
  186.             time.sleep(0.1)
  187.             results.append(self.send_command('\n'))
  188.             requests.append('\n')
  189.  
  190.         resp['request'] = requests
  191.         resp['response'] = results
  192.         return resp
  193.  
  194.     def get(self, command=None, prompt=None, answer=None, sendonly=False, output=None, check_all=False):
  195.         if not command:
  196.             raise ValueError('must provide value of command to execute')
  197.         if output:
  198.             raise ValueError("'output' value %s is not supported for get" % output)
  199.  
  200.         return self.send_command(command=command, prompt=prompt, answer=answer, sendonly=sendonly, check_all=check_all)
  201.  
  202.     def get_option_values(self):
  203.         return {
  204.             'format': ['text'],
  205.             'diff_match': ['line', 'strict', 'exact', 'none'],
  206.             'diff_replace': ['line', 'block'],
  207.             'output': ['text']
  208.         }
  209.  
  210.     def get_capabilities(self):
  211.         result = dict()
  212.         result['rpc'] = self.get_base_rpc()
  213.         result['network_api'] = 'cliconf'
  214.         result['device_info'] = self.get_device_info()
  215.         result['device_operations'] = self.get_device_operations()
  216.         result.update(self.get_option_values())
  217.         return json.dumps(result)
  218.  
  219.  
  220.     def get_device_operations(self):
  221.         return {
  222.             'supports_diff_replace': False,
  223.             'supports_commit': False,
  224.             'supports_rollback': False,
  225.             'supports_defaults': True,
  226.             'supports_onbox_diff': False,
  227.             'supports_commit_comment': False,
  228.             'supports_multiline_delimiter': True,
  229.             'supports_diff_match': False,
  230.             'supports_diff_ignore_lines': False,
  231.             'supports_generate_diff': False,
  232.             'supports_replace': False
  233.         }
  234.  
  235.  
  236. (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible/modules/network/EM316LNXNM/EM316LNXNM_command.py
  237. #!/usr/bin/python
  238.  
  239. from __future__ import (absolute_import, division, print_function)
  240. __metaclass__ = type
  241.  
  242. ANSIBLE_METADATA = {'metadata_version': '1.1',
  243.                     'status': ['preview'],
  244.                     'supported_by': 'community'}
  245.  
  246. import time
  247.  
  248. from ansible.module_utils._text import to_text
  249. from ansible.module_utils.basic import AnsibleModule
  250. from ansible.module_utils.network.common.parsing import Conditional
  251. from ansible.module_utils.network.common.utils import ComplexList
  252. from ansible.module_utils.network.edgeos.edgeos import run_commands
  253. from ansible.module_utils.six import string_types
  254.  
  255. def to_lines(stdout):
  256.     for item in stdout:
  257.         if isinstance(item, string_types):
  258.             item = to_text(item).split('\n')
  259.         yield item
  260.  
  261.  
  262. def parse_commands(module, warnings):
  263.     spec = dict(
  264.         command=dict(key=True),
  265.         prompt=dict(),
  266.         answer=dict(),
  267.     )
  268.  
  269.     transform = ComplexList(spec, module)
  270.     commands = transform(module.params['commands'])
  271.  
  272.     if module.check_mode:
  273.         for item in list(commands):
  274.             if not item['command'].startswith('show'):
  275.                 warnings.append(
  276.                     'Only show commands are supported when using check_mode, '
  277.                     'not executing %s' % item['command'])
  278.                 commands.remove(item)
  279.  
  280.     return commands
  281.  
  282.  
  283. def main():
  284.     spec = dict(
  285.         commands=dict(type='list', required=True),
  286.         wait_for=dict(type='list'),
  287.         match=dict(default='all', choices=['all', 'any']),
  288.         retries=dict(default=10, type='int'),
  289.         interval=dict(default=1, type='int')
  290.     )
  291.  
  292.     module = AnsibleModule(argument_spec=spec, supports_check_mode=True)
  293.  
  294.     warnings = list()
  295.     result = {'changed': False}
  296.     commands = parse_commands(module, warnings)
  297.     wait_for = module.params['wait_for'] or list()
  298.  
  299.     try:
  300.         conditionals = [Conditional(c) for c in wait_for]
  301.     except AttributeError as e:
  302.         module.fail_json(msg=to_text(e))
  303.  
  304.     retries = module.params['retries']
  305.     interval = module.params['interval']
  306.     match = module.params['match']
  307.  
  308.     while retries > 0:
  309.         responses = run_commands(module, commands)
  310.  
  311.         for item in list(conditionals):
  312.             if item(responses):
  313.                 if match == 'any':
  314.                     conditionals = list()
  315.                     break
  316.                 conditionals.remove(item)
  317.  
  318.         if not conditionals:
  319.             break
  320.  
  321.         time.sleep(interval)
  322.         retries -= 1
  323.  
  324.     if conditionals:
  325.         failed_conditions = [item.raw for item in conditionals]
  326.         msg = 'One or more conditional statements have not been satisfied'
  327.         module.fail_json(msg=msg, failed_conditions=failed_conditions)
  328.  
  329.     result = {
  330.         'changed': False,
  331.         'stdout': responses,
  332.         'warnings': warnings,
  333.         'stdout_lines': list(to_lines(responses))
  334.     }
  335.  
  336.     module.exit_json(**result)
  337.  
  338.  
  339. if __name__ == '__main__':
  340.     main()
  341.  
  342. (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible/modules/network/EM316LNXNM/EM316LNXNM_config.py
  343. #!/usr/bin/python
  344.  
  345. ANSIBLE_METADATA = {'metadata_version': '1.1',
  346.                     'status': ['preview'],
  347.                     'supported_by': 'community'}
  348.  
  349. import json
  350.  
  351. from ansible.module_utils._text import to_text
  352. from ansible.module_utils.connection import ConnectionError
  353. from ansible.module_utils.network.EM316LNXNM.EM316LNXNM import run_commands, get_config
  354. from ansible.module_utils.basic import AnsibleModule
  355. from ansible.module_utils.network.common.config import NetworkConfig, dumps
  356.  
  357. def save_config(module, result):
  358.     result['changed'] = True
  359.     if not module.check_mode:
  360.         run_commands(module, 'write file\r')
  361.     else:
  362.         module.warn('Skipping command `write term` due to check_mode. '
  363.                     'Configuration not copied to non-volatile storage')
  364.  
  365. def main():
  366.     spec = dict(
  367.         src=dict(type='path'),
  368.         lines=dict(type='list'),
  369.  
  370.         match=dict(default='line', choices=['line', 'none']),
  371.  
  372.         comment=dict(default=DEFAULT_COMMENT),
  373.  
  374.         config=dict(),
  375.  
  376.         backup=dict(type='bool', default=False),
  377.         save=dict(type='bool', default=False),
  378.     )
  379.  
  380.     mutually_exclusive = [('lines', 'src')]
  381.  
  382.     module = AnsibleModule(
  383.         argument_spec=spec,
  384.         mutually_exclusive=mutually_exclusive,
  385.         supports_check_mode=True
  386.     )
  387.  
  388.     warnings = list()
  389.  
  390.     result = dict(changed=False, warnings=warnings)
  391.  
  392.     if module.params['backup']:
  393.         result['__backup__'] = get_config(module=module)
  394.  
  395.     if any((module.params['src'], module.params['lines'])):
  396.         run(module, result)
  397.  
  398.     running_config = module.params['running_config']
  399.     startup_config = None
  400.  
  401.     if module.params['save_when'] == 'always' or module.params['save']:
  402.         save_config(module, result)
  403.     elif module.params['save_when'] == 'modified':
  404.         output = run_commands(module, ['show running-config', 'show startup-config'])
  405.  
  406.         running_config = NetworkConfig(indent=1, contents=output[0], ignore_lines=diff_ignore_lines)
  407.         startup_config = NetworkConfig(indent=1, contents=output[1], ignore_lines=diff_ignore_lines)
  408.  
  409.         if running_config.sha1 != startup_config.sha1:
  410.             save_config(module, result)
  411.     elif module.params['save_when'] == 'changed' and result['changed']:
  412.         save_config(module, result)
  413.  
  414.     #if module.params['save']:
  415.     #    diff = run_commands(module, commands=['configure', 'compare saved'])[1]
  416.     #    if diff != '[edit]':
  417.     #        run_commands(module, commands=['save'])
  418.     #        result['changed'] = True
  419.     #    run_commands(module, commands=['exit'])
  420.  
  421.     module.exit_json(**result)
  422.  
  423.  
  424. if __name__ == '__main__':
  425.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement