def routerLogin(): # This function prompts the user to provide their login credentials and logs into each # of the routers before calling the buildIndex function to extract relevant portions of # the router config. As designed, this function actually has the capability to login to # multiple routers simultaneously. I chose to not allow it to multi-thread given possibility # of undesirable results from multiple threads writing to the same index file simultaneously try:# Check for existence of routerFile; If exists, continue with program with open(routerFile, "r"): pass # Read hosts from specified file & remove duplicate entries, set protocol to SSH2 hosts = get_hosts_from_file(routerFile,default_protocol="ssh2",remove_duplicates=True) if username == "": # If username is blank print account = read_login() # Prompt the user for login credentials elif password == "": # If password is blank print account = read_login() # Prompt the user for login credentials else: # Else use username/password from configFile account = Account(name=username, password=b64decode(password)) # Minimal message from queue, 1 threads, redirect errors to null queue = Queue(verbose=0, max_threads=1, stderr=(open(os.devnull, "w"))) queue.add_account(account) # Use supplied user credentials print stdout.write("--> Building index...") # Print without trailing newline queue.run(hosts, buildIndex) # Create queue using provided hosts queue.shutdown() # End all running threads and close queue # If logFileDirectory does not exist, create it. if not path.exists(logFileDirectory): makedirs(logFileDirectory) # Define log filename based on date logFilename = logFileDirectory+"VRFSearchAndBackup_"+date+".log" # Check to see if logFilename currently exists. If it does, append an # integer onto the end of the filename until logFilename no longer exists incrementLogFilename = 1 while fileExist(logFilename): logFilename = logFileDirectory+"VRFSearchAndBackup_"+date+"_"+str(incrementLogFilename)+".log" incrementLogFilename = incrementLogFilename + 1 # Write log results to logFile with open(logFilename, "w") as outputLogFile: try: outputLogFile.write(summarize(logger)) # Exception: router file was not able to be opened except IOError: print print "--> An error occurred opening "+logFileDirectory+logFile+"." # Exception: router file could not be opened except IOError: print print "--> An error occurred opening "+routerFile+"."
def __init__(self, io): self.hosts = [] self.accounts = [] self.io = io self.hosts = get_hosts_from_file(self.io.rootDir + "/" + "hosts") logging.info("read in hosts" + self.io.rootDir + "/" + "hosts") if not self.hosts: logging.info("EMPTY HOST FILE, exit ...") exit(1) for h in self.hosts: logging.info("host:" + h.get_address()) self.accounts = get_accounts_from_file(io.rootDir + "/" + "accounts") logging.info("read in accounts" + self.io.rootDir + "/" + "accounts") if not self.accounts: logging.info("EMPTY ACCOUNT FILE, exit ...") exit(1) for a in self.accounts: logging.info("account:" + a.get_name())
pic = optic.getparent().find('{0}name'.format(namespace)).text mic = optic.getparent().getparent().find('{0}name'.format(namespace)).text fpc = optic.getparent().getparent().getparent().find('{0}name'.format(namespace)).text intf = fpc.split(" ")[1]+"/"+ pic.split(" ")[1] +"/"+name.split(" ")[1] f.write(description + "\t\t\t" + intf + "\t\t\t" + "Serial: " + serial + "\n") f.close() # Read input data. #accounts = get_accounts_from_file('accounts.cfg') accounts = read_login() try: hosts = get_hosts_from_file('hostlist.txt') except: print """ Devi creare un file che si chiama hostlist.txt e dentro ci sono linee di questo tipo: ssh://r.rm2.garr.net """ sys.exit(0) # Run do_something on each of the hosts. The given accounts are used # round-robin. "verbose = 0" instructs the queue to not generate any # output on stdout. queue = Queue(verbose = 3, max_threads = 5) queue.add_account(accounts) # Adds one or more accounts. queue.run(hosts, do_something) # Asynchronously enqueues all hosts.
from Exscript.util.start import quickstart from Exscript.util.match import first_match from Exscript import Host, Account from Exscript.util.start import start from Exscript.util.file import get_hosts_from_file account1 = Account('YOURUSERNAME ', 'YOURPASSWORD') host1 = get_hosts_from_file('LISTOFIP.txt') #host1 = Host('ssh://IPADDRESS') errorList = [] def do_something(job, host, conn): try: conn.execute('sh run | i hostname') error = conn.response.split('\n') conn.execute('sh run | i enable secret') output = conn.response.split('\n') #print(output) final = [] for x in output: if (x.startswith('enable secret')): y = x.replace("\r", '') final.append(y) conn.execute('sh run | i enable password') output = conn.response.split('\n')
from Exscript.util.start import quickstart from Exscript.util.file import get_hosts_from_file, get_accounts_from_file from Exscript import Account command = input("enter command: ") def do_something(job, host, conn): conn.execute('term len 0') conn.execute(command) accounts = get_accounts_from_file('accounts.cfg') hosts = get_hosts_from_file('hostlist.txt', default_protocol='ssh2') quickstart(hosts, do_something, max_threads=15, verbose=1)
import Exscript.util.file as euf import Exscript.util.start as eus import Exscript.util.match as eum import pysvn import os import time import datetime hosts = euf.get_hosts_from_file('c:\\network_configs\\hosts.txt') accounts = euf.get_accounts_from_file('c:\\network_configs\\accounts.cfg') def dump_config(job, host, conn): """Connect to device, trim config file a bit, write to file""" conn.execute('term len 0') conn.execute('show run') #get the actual hostname of the device hostname = eum.first_match(conn, r'^hostname\s(.+)$') cfg_file = 'c:\\network_configs\\' + hostname.strip() + '.cfg' config = conn.response.splitlines() # a little cleanup for i in range(3): config.pop(i) config.pop(-0) config.pop(-1) # write config to file with open(cfg_file, 'w') as f: for line in config: f.write(line +'\n') eus.start(accounts, hosts, dump_config, max_threads=2)
date = datetime.now() # Determine today's date date = date.strftime("%Y%m%d") # Format date as YYYYMMDD if username == "": # If username is blank print account = read_login() # Prompt the user for login credentials elif password == "": # If password is blank print account = read_login() # Prompt the user for login credentials else: # Else use username/password from configFile account = Account(name=username, password=b64decode(password)) # Read hosts from specified file & remove duplicate entries, set protocol to SSH2 hosts = get_hosts_from_file(routerFile, default_protocol="ssh2", remove_duplicates=True) print # Verbose & # threads taken from configFile, redirect errors to null queue = Queue(verbose=int(verboseOutput), max_threads=int(maxThreads), stderr=(open(os.devnull, "w"))) queue.add_account(account) # Use supplied user credentials queue.run(hosts, downloadRouterConfig) # Create queue using provided hosts queue.shutdown() # End all running threads and close queue print status(logger) # Print current % status of operation to screen # If logFileDirectory does not exist, create it. if not path.exists(logFileDirectory): makedirs(logFileDirectory) # Define log filename based on date
#!/usr/bin/env python import Exscript.util.file as euf import Exscript.util.start as eus import Exscript.util.match as eum from Exscript import Account hosts = euf.get_hosts_from_file('ips.txt') threads = 8 print "\nClearing crypto sa sessions with: " + str(threads) + " threads\n" def clear_sa(job, hosts, conn): conn.execute('clear crypto sa') eus.quickstart(hosts, clear_sa, max_threads=threads)
raise Exception('unsupported os: ' + repr(conn.guess_os())) # autoinit() automatically executes commands to make the remote # system behave more script-friendly. The specific commands depend # on the detected operating system, i.e. on what guess_os() returns. conn.autoinit() # Execute a simple command. conn.execute('show ip int brie') print "myvariable is", conn.get_host().get('myvariable') def two(conn): conn.autoinit() conn.execute('show interface POS1/0') accounts = get_accounts_from_file('accounts.cfg') # Start on one host. host = Host('localhost') host.set('myvariable', 'foobar') start(accounts, host1, one) # Start on many hosts. In this case, the accounts from accounts.cfg # are only used if the host url does not contain a username and password. # The "max_threads" keyword indicates the maximum number of concurrent # connections. hosts = get_hosts_from_file('hostlist.txt') start(accounts, hosts, two, max_threads=2)
#!/usr/bin/env python import Exscript.util.file as euf import Exscript.util.start as eus import Exscript.util.match as eum # import Exscript.protocols.drivers from Exscript import Account hosts = euf.get_hosts_from_file('hosts_mass_config.txt') def mass_commands(job, hosts, conn): # conn.send("enable\r") # conn.auto_app_authorize(accounts) conn.execute('conf t') mass_commands_file = 'mass_commands.txt' with open(mass_commands_file, 'r') as f: for line in f: conn.execute(line) # conn.execute('show run') # get hostname of the device # hostname = eum.first_match(conn, r'^hostname\s(.*)$') # cfg_file = '/home/xxxx/python/configs/firewalls/' + hostname.strip() + '.cfg' # config = conn.response.splitlines() # some clean up # for i in range(3): # config.pop(i) # config.pop(-0) # config.pop(-1) # write config to file
elif task == 'NO_DIVERT' and valid_ipv4(ipaddr): conn.execute('term len 0') conn.execute('conf t') conn.execute('ip access-list extended NORMAL') conn.execute('no permit ip any any') conn.execute(f"no deny ip {ipaddr} {wildcard}") conn.execute(f"permit ip any any") conn.execute('ip access-list extended DIVERT') conn.execute('no deny ip any any') conn.execute(f"no permit ip {ipaddr} {wildcard}") conn.execute('deny ip any any') conn.execute('end') conn.execute('clear ip bgp * soft out') else: RED = '\033[31m' print(RED + "\nWARNING: \tPLEASE INPUT A CORRECT TASK AND IP ADDRESS!") print(f"NOTE:\t\tNO CHANGES HAS BEEN MADE!") print(Style.RESET_ALL) # Read input data. accounts = get_accounts_from_file('/root/crash_course/project/accounts.cfg') hosts = get_hosts_from_file('/root/crash_course/project/hostlist.txt',default_protocol='ssh2') queue = Queue(max_threads=5) queue.add_account(accounts) queue.run(hosts, do_something,) queue.shutdown()
def get_switch_list(): switch_list = raw_input('Where is the list of switches stored? ') hosts = get_hosts_from_file(switch_list) start(accounts, hosts, turn_off_install, max_threads=2)
import Exscript from Exscript.util.start import quickstart from Exscript.util.file import get_hosts_from_file def do_something(job, host, conn): conn.execute('conf t') conn.execute('interface lo4') conn.execute('des exscript') conn.execute('end') hosts = get_hosts_from_file('hosts.txt') quickstart(hosts, do_something, max_threads=3) #quickstart does the following: #1.It prompts the user for a username and a password. #2.It connects to the specified host, using the specified protocol. #3.It logs in using the given login details. #4.It calls our do_something() function. #5.When do_something() completes, it closes the connection. #max_threads = 3 does the following: #This tells Exscript to open three network connections in parallel.
import Exscript from Exscript.util.start import quickstart from Exscript.util.file import get_hosts_from_file def do_something(job, host, conn): conn.execute('conf t') conn.execute('interface lo4') conn.execute('des exscript') conn.execute('end') hosts = get_hosts_from_file('hosts.txt') quickstart(hosts, do_something, max_threads = 3) #quickstart does the following: #1.It prompts the user for a username and a password. #2.It connects to the specified host, using the specified protocol. #3.It logs in using the given login details. #4.It calls our do_something() function. #5.When do_something() completes, it closes the connection. #max_threads = 3 does the following: #This tells Exscript to open three network connections in parallel.
def testGetHostsFromFile(self): from Exscript.util.file import get_hosts_from_file result = get_hosts_from_file(self.host_file.name) self.assertEqual([h.get_name() for h in result], expected_hosts)
raise Exception("unsupported os: " + repr(conn.guess_os())) # autoinit() automatically executes commands to make the remote # system behave more script-friendly. The specific commands depend # on the detected operating system, i.e. on what guess_os() returns. conn.autoinit() # Execute a simple command. conn.execute("show ip int brie") print "myvariable is", conn.get_host().get("myvariable") def two(job, host, conn): conn.autoinit() conn.execute("show interface POS1/0") accounts = get_accounts_from_file("accounts.cfg") # Start on one host. host = Host("localhost") host.set("myvariable", "foobar") start(accounts, host, one) # Start on many hosts. In this case, the accounts from accounts.cfg # are only used if the host url does not contain a username and password. # The "max_threads" keyword indicates the maximum number of concurrent # connections. hosts = get_hosts_from_file("hostlist.txt") start(accounts, hosts, two, max_threads=2)