Skip to content

Instantly share code, notes, and snippets.

@coxley
Last active August 29, 2015 14:11
Show Gist options
  • Save coxley/c4f3a03303d7a670670c to your computer and use it in GitHub Desktop.
Save coxley/c4f3a03303d7a670670c to your computer and use it in GitHub Desktop.
various helper functions
import sys
import time
import logging
import socket
import Exscript.protocols as protocols
from Exscript.util.interact import read_login
from Exscript.util.file import get_hosts_from_file
from Exscript.protocols.Exception import LoginFailure, TimeoutException
def create_logger(log_path, filename):
logFormatter = logging.Formatter(
"%(asctime)s [%(levelname)-5.5s] %(message)s")
rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.INFO)
fileHandler = logging.FileHandler("{0}/{1}.log".format(log_path, filename))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
return rootLogger
# logger = create_logger('./', 'add_syslog.log')
class MyLogger(object):
'''Temporary logger object to get around Exscript overriding logging'''
def _write(self, log, file_path='log.txt'):
'''Private method to write to log file
:param log: Message to log
:type log: str
:param file_path: Path to file to log
:type file_path: str
'''
with open(file_path, 'a') as f:
f.write(log + '\n')
def info(self, message):
'''Informational log
:param message: Message to log
:type message: str
'''
curtime = time.strftime("%Y-%m-%d %H:%M:%S")
log = "{0} [{1}]: {2}".format(curtime, 'INFO', message)
print log
self._write(log)
def critical(self, message):
'''Critical log
:param message: Message to log
:type message: str
'''
curtime = time.strftime("%Y-%m-%d %H:%M:%S")
log = "{0} [{1}]: {2}".format(curtime, 'CRITICAL', message)
print log
self._write(log)
logger = MyLogger()
def connect_to_host(host, account, driver='ios'):
'''Connect and login to host and return connection object
:param host: Host in URI form
:type host: str
:param account: Account for log into devices
:type account: Exscript Account object
:param driver: Driver string. Defaults to 'ios'
:type driver: str
'''
try:
conn = protocols.connect(host)
except socket.error, e:
logger.critical('({}) - {}'.format(host.address, e))
return False
try:
conn.set_driver(driver)
except TypeError:
conn.set_driver('ios')
try:
conn.login(account)
except LoginFailure, e:
logger.critical('({}) - {}'.format(host.address, e))
return False
except TimeoutException, e:
logger.critical('({}) - {}'.format(host.address, e))
return False
return conn
def add_syslog_host(conn, syslog_host,
syntax='ios', ifname='inside'):
'''Configure syslog host and global trap severity level. Assumes config lvl
:param conn: Exscript connection object
:param syslog_host: IP address or hostname of syslog host
:type syslog_host: str
:param syntax: Configuration syntax to use. 'ios' default. Can use 'asa'.
:type syntax: str
:param ifname: Used for ASA interface name. Optional. Will default 'inside'
:type ifname: str
'''
if syntax == 'ios':
conn.execute('logging host {}'.format(syslog_host))
elif syntax == 'asa':
conn.execute('logging host {} {}'.format(ifname, syslog_host))
else:
logger.error('ERROR: Incorrect syntax provided.')
return False
conn.execute('logging trap warnings')
logger.info('Syslog host added.')
return
@coxley
Copy link
Author

coxley commented Dec 17, 2014

Example for adding syslog to group of hosts:

def run(hosts, account, device_type='ios'):
    '''Run
    :param hosts: Hosts
    :type hosts: list of str of hosts in URI form OR Exscript Hosts
    :param account: Account to use for logging into hosts
    :type account: Exscript Account object
    :param device_type: Device type
    :type device_type: str of either 'ios' or 'asa'
    '''
    for host in hosts:
        conn = connect_to_host(host, account)
        if not conn:
            continue
    logger.info('Connected successfully to {}'.format(host.address))
    conn.execute('configure terminal')
    if device_type == 'ios':
        add_syslog_host(conn, '10.0.0.100')
    elif device_type == 'asa':
        add_syslog_host(conn, '10.0.0.100', syntax='asa', ifname='inside')
    conn.execute('end')
    logger.info('Saving config')
    conn.execute('wr')
    conn.send('exit\r')
    conn.close()
    logger.info('Finished with {}'.format(host.address))



account = read_login()

rtr_hosts = get_hosts_from_file('hosts-rtr.txt')
sw_hosts = get_hosts_from_file('hosts-sw.txt')
ios_hosts = rtr_hosts + sw_hosts
asa_hosts = get_hosts_from_file('hosts-asa.txt')

logger.info('Starting IOS hosts')
run(ios_hosts, account)

logger.info('Starting ASA hosts')
run(asa_hosts, account, device_type='asa')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment