def run_command(rmq_channel, command, hosts, threads): """Execute command on remote host""" from Exscript import Account, Host from Exscript.util.start import start results = {} def do_something(thread, host, conn): #conn.execute('vtysh -c "%s"' % command) conn.execute(command) result = repr(conn.response) data = { host.address: { command: result }, } body = json.dumps(data) rmq_channel.basic_publish(exchange='measure', routing_key="result", body=body) #conn.execute("exit") accounts = [Account("root", password="******")] hosts = [Host(h, default_protocol="ssh") for h in hosts] #TODO: open multiple ssh sessions start(accounts, hosts, do_something, max_threads=threads) return results
def run_command(rmq_channel, command, hosts, threads): """Execute command on remote host""" from Exscript import Account, Host from Exscript.util.start import start from Exscript.util.match import first_match, any_match from Exscript import PrivateKey from Exscript.util.template import eval_file from Exscript.protocols.Exception import InvalidCommandException results = {} def do_something(thread, host, conn): #conn.execute('vtysh -c "%s"' % command) conn.execute(command) result = repr(conn.response) data = { host.address: {command: result}, } body = json.dumps(data) rmq_channel.basic_publish(exchange='measure', routing_key = "result", body= body) #conn.execute("exit") accounts = [Account("root")] hosts = [Host(h, default_protocol = "ssh") for h in hosts] #TODO: open multiple ssh sessions start(accounts, hosts, do_something, max_threads = threads) return results
def clear(): def clearall(job,host,conn): conn.execute('configure') conn.execute('delete webui data-stores') conn.execute('delete topology') conn.execute('delete devices device') conn.execute('commit') start(account,host,clearall)
def option(number): print('\r') if number == 1: start(accounts, switch, show_int, max_threads=2) run_job() elif number == 2: print('\r') start(accounts, switch, show_mac, max_threads=2) run_job() elif number == 3: print('\r') start( accounts, switch, power_cycle, max_threads=2 ) # calling the start function to take all variables and input into reboot_device function. run_job() elif number == 4: print('\r') get_switch_ip() run_job() elif number == 5: print('\r') get_switch_list() run_job() elif number == 6: exit_script()
def upload(jsondata,coorddata): def do_addnode(job,host,conn,node): conn.execute('configure') conn.execute('set devices authgroups group auth-cisco default-map remote-name cisco remote-password cisco remote-secondary-password cisco') conn.execute('commit') conn.execute('set devices device '+node['NodeName']+' address '+node['managementIP']+' port '+portmapping[node['managementProtocol']]+' authgroup auth-cisco device-type cli ned-id '+iosmapping[node["NodeSubtype"]]+' protocol '+node['managementProtocol'] ) conn.execute('commit') conn.execute('set devices device '+node['NodeName']+' state admin-state unlocked ') conn.execute('commit') conn.execute('request devices device '+node['NodeName']+' sync-from') def get_int_info(device,connex): for node in jsondata: if node["NodeName"]==device : for int in node["Interface"]: if(connex==int['network']): return int['name'], int['ip-address'] def do_addconnection(job,host,conn,node1,node2,interface): info1=get_int_info(node1,interface) info2=get_int_info(node2,interface) conn.execute('configure') try: if info1[1]=="None": conn.execute('set topology connection '+node1+"_"+node2+' endpoint-1 device '+node1+" interface "+info1[0]) conn.execute('set topology connection '+node1+"_"+node2+' endpoint-2 device '+node2+" interface "+info2[0]) else: conn.execute('set topology connection '+node1+"_"+node2+' endpoint-1 device '+node1+" interface "+info1[0]+ " ip-address "+info2[1]) conn.execute('set topology connection '+node1+"_"+node2+' endpoint-2 device '+node2+" interface "+info2[0]+ " ip-address "+info2[1]) conn.execute('commit') except Exception as e: print e print info1,info2 def do_addicons(job,host,conn,node,coordx,coordy): conn.execute("configure") conn.execute('set webui icons device '+node['NodeName']+' disabled large icon cisco-disabled') conn.execute('set webui icons device '+node['NodeName']+' enabled large icon cisco-enabled') conn.execute('set webui data-stores static-map device '+node['NodeName']+' coord x '+str(coordx)+' y '+str(coordy)+'') conn.execute('commit') for node in jsondata : for i in range (0,len(coorddata)): if coorddata[i][0]==node['NodeName']: coordx=coorddata[i][1] coordy=coorddata[i][2] break start(account, host, bind(do_addnode,node)) start(account, host, bind(do_addicons,node,coordx,coordy)) for interfaces in node['Interface']: split=interfaces['network'].split("-to-",2) if len(split) ==2: start(account, host, bind(do_addconnection,split[0],split[1],interfaces['network']))
# crash_id may not be set, if machine not present in initial vlist, if so then ignore log.info('Stopping running VM %s' % virtual_machine) conn.execute('vcrash %s' % crash_id) time.sleep(1) else: # conn.execute(start_command) lab_is_started = True first_match(conn, r'^The lab has been started') log.info('Lab started' ) # TODO: make this captured - need to debug capturing conn.send('exit') if key_filename: key = PrivateKey.from_file(key_filename) log.debug('Connecting to %s with username %s and key %s' % (host, username, key_filename)) accounts = [Account(username, key=key)] else: log.debug('Connecting to %s with username %s' % (host, username)) accounts = [Account(username)] hosts = ['ssh://%s' % host] verbosity = -1 start(accounts, hosts, start_lab, verbose=verbosity)
# crash_id may not be set, if machine not present in initial vlist, if so then ignore log.info('Stopping running VM %s' % virtual_machine) conn.execute('vcrash %s' % crash_id) time.sleep(1) else: # conn.execute(start_command) lab_is_started = True first_match(conn, r'^The lab has been started') log.info('Lab started') # TODO: make this captured - need to debug capturing conn.send('exit') if key_filename: key = PrivateKey.from_file(key_filename) log.debug('Connecting to %s with username %s and key %s' % (host, username, key_filename)) accounts = [Account(username, key=key)] else: log.debug('Connecting to %s with username %s' % (host, username)) accounts = [Account(username)] hosts = ['ssh://%s' % host] verbosity = -1 start(accounts, hosts, start_lab, verbose=verbosity)
if (x.startswith('enable password')): y = x.replace("\r", '') final.append(y) conn.execute('conf t') #print(final) for x in final: noUser = '******' + x print(noUser) conn.execute(noUser + '\n') #conn.execute('') #print(final) #conn.execute('conf t') conn.execute('end') conn.execute('wr mem') except: for x in error: if (x.startswith('hostname')): y = x.replace("\r", '') errorList.append(y) print(errorList) start(account1, host1, do_something, max_threads=3)
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)
conn.execute('cd %s' % cd_dir) conn.execute('vlist') conn.execute("lclean") log.info("Starting lab") start_command = 'lstart -p5 -o --con0=none' try: conn.execute(start_command) except InvalidCommandException, error: if "already running" in str(error): time.sleep(1) #print "Already Running" #TODO: handle appropriately #print "Halting previous lab" #conn.execute("vclean -K") #print "Halted previous lab" #conn.execute("vstart taptunnelvm --con0=none --eth0=tap,172.16.0.1,172.16.0.2") # TODO: don't hardcode this #print "Starting lab" conn.execute(start_command) first_match(conn, r'^The lab has been started') conn.send("exit") #TODO: need to capture and handle tap startup if key_filename: key = PrivateKey.from_file(key_filename) accounts = [Account(username, key = key)] else: accounts = [Account(username)] hosts = ['ssh://%s' % host] start(accounts, hosts, do_something, verbose = 0)
def parallelExec(self): start(self.accounts, self.hosts, self.command_loop, max_threads = 5)
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)
# You can add a safehold based on the guess_os() method. if conn.guess_os() != 'ios': 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, 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)
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)
def do_something(thread, host, conn): conn.add_monitor(r'Starting (\S+)', starting_host) conn.add_monitor(r'The lab has been started', lab_started) #conn.data_received_event.connect(data_received) conn.execute('tar -xzf %s' % tar_file) conn.execute('cd %s' % cd_dir) conn.execute('vlist') conn.execute("lclean") print "Starting lab" start_command = 'lstart -p5 -o --con0=none' try: conn.execute(start_command) except InvalidCommandException, error: if "already running" in str(error): print "Already Running" #TODO: handle appropriately print "Halting previous lab" conn.execute("vclean -K") print "Halted previous lab" print "Starting lab" conn.execute(start_command) first_match(conn, r'^The lab has been started') print "HERE" conn.send("exit") #TODO: need to capture and handle tap startup accounts = [Account("sknight")] hosts = ['ssh://%s' % host] start(accounts, hosts, do_something, verbose = 2)