Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- """
- Loop over a list of devies in a YAML file and print their OS version
- sudo -H pip3 install napalm
- inventory.yml:
- ---
- # required: hostname, os
- # optional: username, password, timeout, optional_args
- R1:
- hostname: 192.168.223.2
- os: ios
- username: admin
- password: admin
- optional_args:
- secret: enable
- transport: telnet # Default is SSH
- port: 23
- verbose: True
- R2:
- hostname: 192.168.188.2
- os: ios
- """
- import argparse
- from getpass import getpass
- import napalm
- import sys
- import yaml
- def parse_cli_args():
- parser = argparse.ArgumentParser(
- description='Loop over a list of devices in a YAML file and print the device firmware version',
- formatter_class=argparse.ArgumentDefaultsHelpFormatter,
- )
- parser.add_argument(
- '-i', '--inventory-file',
- help='Input YAML inventory file',
- type=str,
- default='inventory.yml',
- )
- parser.add_argument(
- '-u', '--username',
- help='Default username for device access',
- type=str,
- default=None,
- )
- return vars(parser.parse_args())
- def main():
- args = parse_cli_args()
- args['password'] = getpass("Default password:")
- try:
- inventory_file = open(args['inventory_file'])
- except Exception:
- print('Couldn\'t open inventory file {}'.format(args['inventory_file']))
- try:
- inventory = yaml.load(inventory_file)
- except Exception:
- return 1
- inventory_file.close()
- for dev, opt in inventory.items():
- if 'username' not in opt:
- if not args['username']:
- print ('No username specified')
- return 1
- else:
- opt['username'] = args['username']
- if 'password' not in opt:
- opt['password'] = args['password']
- if 'optional_args' not in opt:
- opt['optional_args'] = None
- driver = napalm.get_network_driver(opt['os'])
- opt.pop('os')
- with driver(**opt) as device:
- print('{}: {}'.format(opt['hostname'], device.get_facts()['os_version']))
- return 0
- if __name__ == '__main__':
- sys.exit(main())
Add Comment
Please, Sign In to add comment