def get_configs(proto, account, host, t_out=30): try: if proto == "ssh": if t_out == 30: conn = SSH2() else: conn = SSH2(timeout=t_out) elif proto == "telnet": conn = Telnet() conn.set_driver('ios') conn.connect(host) conn.login(account) conn.execute('term length 0') conn.execute('term width 0') conn.send('enable\r') conn.app_authorize(account) conn.execute('show version') showver = conn.response.split('\r\n') conn.execute('show startup-config') showstart = conn.response.split('\r\n') conn.execute('show running-config all') showrun = conn.response.split('\r\n') showrun.pop() showstart.pop() showver.pop() outputbuffer = {'version':showver, 'startup-config':showstart, 'running-config':showrun, 'error': None} return outputbuffer except Exception: outputbuffer = {'version': "", 'startup-config': "", 'running-config':"", 'error': True} return outputbuffer
def execute_controller_command_return_output(self, input, controllerRole): '''Execute a generic command on the controller and return ouput. Input: controllerRole Where to execute the command. Accepted values are `Master` and `Slave` input Command to be executed on switch Return Value: Output from command execution Example: |${syslog_op}= | execute switch command return output | 10.192.75.7 | debug ofad 'help; cat /var/log/syslog | grep \"Disabling port port-channel1\"' | ''' t = test.Test() if (controllerRole == 'Master'): c = t.controller('master') else: c = t.controller('slave') conn = SSH2() conn.connect(c.ip) conn.login(Account("admin", "adminadmin")) conn.execute('enable') conn.execute('debug bash') conn.execute(input) output = conn.response conn.send('logout\r') conn.send('logout\r') conn.close() return output
def delete_snmp_keyword(self, ip_address, snmpKey, snmpValue): ''' Delete SNMP Key/Value Input: ip_address IP Address of switch snmpKey SNMP Key like location, community etc snmpValue Value corresponding to SNMP Key ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') conn.execute('conf t') input = "no snmp-server %s %s" % (str(snmpKey), str(snmpValue)) conn.execute(input) conn.send('exit\r') conn.send('exit\r') conn.send('exit\r') conn.close() return True except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def sshdevice(account, device, cmdlist, fileprefix): conn = SSH2() conn.connect(device) conn.login(account) out = '' bar = progressbar.ProgressBar(max_value=4) i = 0 for cmd in cmdlist: conn.execute(cmd) out = conn.response if cmd == 'show access-list': logfile = fileprefix + 'acl_original.txt' log = io.open(logfile, 'w', encoding='utf8') log.write(out) log.close() elif cmd == 'show route': logfile = fileprefix + 'routing.txt' log = io.open(logfile, 'w', encoding='utf8') log.write(out) log.close() elif cmd == 'show run access-group': logfile = fileprefix + 'accessgroup.txt' log = io.open(logfile, 'w', encoding='utf8') log.write(out) log.close() i = i + 1 bar.update(i) conn.send('exit\r') conn.close() bar.finish()
def return_intf_state(self, ip_address, intf_name): '''Return the Interface State of a given interface on a switch Input: ip_address IP Address of switch intf_name Interface Name eg. ethernet1 or portchannel1 Returns: Interface State of interface. ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) input = "show interface " + str(intf_name) + " detail" conn.execute(input) content = string.split(conn.response, '\n') helpers.log("Value in content[1] is '%s' " % (content[1])) (firstvalue, colon, lastvalue) = content[1].rstrip('\n').strip().split(' ') intf_state = lastvalue.rstrip('\n') helpers.log("Value in content[1] is %s \n and intf_state is %s" % (content[1], intf_state)) return intf_state except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def show_interfaces(self, ip_address): '''Verify all 52 interfaces are seen in switch ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') count = 1 intf_pass_count = 0 while count < 53: intf_name = "ethernet" + str(count) input = "show interface ethernet" + str(count) + " detail" conn.execute(input) if intf_name in conn.response: intf_pass_count = intf_pass_count + 1 helpers.log("Interface %s \n Output is %s \n ======\n" % (intf_name, conn.response)) count = count + 1 conn.send('logout\r') conn.close() if intf_pass_count == 52: return True else: return False except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def change_interface_state_bshell(self, ip_address, interface_num, state): ''' Shut/Unshut interface via broadcom shell command. This can be used only if it is an internal image. Input: ip_address IP Address of Switch interface_name Interface Name state Yes="shutdown", No="no shutdown" ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') conn.execute('conf t') if state == "yes" or state == "Yes": input = 'debug ofad "help; ofad-ctl bshell port ' + str( interface_num) + ' enable=0"' else: input = 'debug ofad "help; ofad-ctl bshell port ' + str( interface_num) + ' enable=1"' conn.execute(input) conn.send('logout\r') conn.close() return True except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def execute_switch_command_return_output(self, ip_address, input): '''Execute a generic command on the switch and return ouput. Input: ip_address IP Address of Switch input Command to be executed on switch Return Value: Output from command execution Example: |${syslog_op}= | execute switch command return output | 10.192.75.7 | debug ofad 'help; cat /var/log/syslog | grep \"Disabling port port-channel1\"' | ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') helpers.sleep(float(1)) conn.execute(input) helpers.sleep(float(1)) output = conn.response conn.send('logout\r') helpers.log("Input is '%s' \n Output is %s" % (input, output)) conn.close() return output except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def flap_eth0_controller(self,controllerRole): ''' Flap eth0 on Controller Input: controllerRole Where to execute the command. Accepted values are `Master` and `Slave` Return Value: True if the configuration is successful, false otherwise ''' t=test.Test() if (controllerRole=='Master'): c= t.controller('master') else: c= t.controller('slave') conn = SSH2() conn.connect(c.ip) conn.login(Account("admin","adminadmin")) conn.execute('debug bash') conn.execute("echo '#!/bin/bash' > test.sh") conn.execute("echo 'sleep 15' >> test.sh") conn.execute("echo 'sudo ifconfig eth0 down' >> test.sh") conn.execute("echo 'sleep 10' >> test.sh") conn.execute("echo 'sudo ifconfig eth0 up' >> test.sh") conn.execute("echo 'sleep 10' >> test.sh") conn.execute("sh test.sh &") helpers.sleep(float(30)) conn.send('exit\r') conn.close() return True
def change_interface_state(self, ip_address, interface_name, state): ''' Shut/Unshut interface via CLI Input: ip_address IP Address of Switch interface_name Interface Name state Yes="shutdown", No="no shutdown" ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') conn.execute('conf t') if state == "yes" or state == "Yes": input = "interface " + str(interface_name) + " shutdown" else: input = "no interface " + str(interface_name) + " shutdown" conn.execute(input) conn.send('logout\r') conn.close() return True except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def return_intf_macaddress(self, ip_address, intf_name): '''Return the MAC/Hardware address of a given interface on a switch Input: ip_address IP Address of switch intf_name Interface Name eg. ethernet1 or portchannel1 Returns: MAC/Hardware address of interface on success. ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) input = "show interface " + str(intf_name) + " detail" conn.execute(input) content = string.split(conn.response, '\n') (firstvalue, colon, lastvalue) = content[2].strip().partition(':') lastvalue = str(lastvalue).rstrip('\n').replace(" ", "") mac_address = lastvalue.rstrip('\n') helpers.log("Value in content[1] is %s \n and mac address is %s" % (content[1], mac_address)) return mac_address except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def verify_portchannel(self, ip_address, pcNumber): '''Verify portchannel shows as up Input: ip_address IP Address of switch pcNumber PortChannel number. Range is between 1 and 30 Returns: true if interface is up, false otherwise ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') intf_name = "port-channel" + pcNumber input = "show interface " + intf_name conn.execute(input) helpers.log("Multiline is %s" % (string.split(conn.response, '\n'))) lagNumber = 60 + int(pcNumber) input1 = str(lagNumber) + "* " + intf_name if str(input1) in conn.response: return True else: return False except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def unconfigure_portchannel(self, ip_address, pcNumber): '''Unconfigure port-channel Inputs: ip_address IP Address of switch pcNumber PortChannel number. Range is between 1 and 30 Returns: True if configuration is a success or False otherwise Examples: | unconfigure portchannel | 10.192.75.7 | 1 | ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') conn.execute('conf t') input = "no port-channel " + str(pcNumber) + " " conn.execute(input) conn.send('logout\r') conn.close() return True except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def get_result(): try: data = request.get_json(True) address = data['host'] account = Account(name=data['user'], password=data['passwd']) if data['conntype'] == 'SSH': from Exscript.protocols import SSH2 conn = SSH2() elif data['conntype'] == 'Telnet': from Exscript.protocols import Telnet conn = Telnet() else: raise (Exception('Unsupport connection type')) conn.connect(address) conn.login(account) conn.execute(data['command']) response = to_plain(str(conn.response)) conn.send('exit\n') conn.close() return jsonify(success=True, response=response) except Exception as e: return jsonify( success=False, response="Opus! Some guy poisoned my coffee last night!")
def verify_portchannel_members(self, ip_address, pc_number, intf_name): '''Verify if portchannel contains the member interface that was configured Input: ip_address IP Address of switch pcNumber PortChannel number. Range is between 1 and 30 intf_name Interface name of member interface Returns: true if member interface is present, false otherwise ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) input = "show port-channel " + str(pc_number) conn.execute(input) content = string.split(conn.response, '\n') helpers.log("Length of content %d" % (len(content))) if len(content) < 8: return False else: for i in range(8, len(content)): intfName = ' '.join(content[i].split()).split(" ", 2) helpers.log('intfName is %s' % intfName) if len(intfName) > 1 and intfName[1] == intf_name: helpers.log("IntfName is %s \n" % (intfName[1])) return True return False except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def login(switch, username, password, verbose): conn = SSH2() #conn = Telnet() #You want to use Telnet? really?! sigh, well I probably cannot stop you... conn.debug = 0 #Exscript debugging info 0-5 if verbose == 1: conn.stdout = sys.stdout #To get line-by-line input/output from the switch conn.connect(switch) #SSH/Telnet connect account = Account(name=username, password='', password2=password) conn.login(account) #enable login return conn
def set_connection(host, login, password, driver='ios'): ''' set_connection configures Exscript SSH2 Connection and validate the device type. Parameters ---------- host : str device to connect to login: str login credential password: str password credential driver : str, optional base driver to test. Returns ------- connection: Exscript.protocols.SSH2 SSH2 object usable with proper driver. ''' logs = [] LOGGER = logging.getLogger(__SCRIPT__) connection = SSH2(driver=driver, debug=0, verify_fingerprint=False, connect_timeout=7, timeout=100, termtype='vt100') connection.connect(str(host).strip()) account = Account(login, password) for attempt in range(4): try: connection.authenticate(account) break except LoginFailure: time.sleep(0.5 + (float(attempt) / 2)) LOGGER.error('Login attempt number %d failed for host %s.', attempt + 1, host) if attempt == 3: raise CiscomationLoginFailed( ('4 Login Failure be careful your login' ' could be locked')) logs.append(('info', 'Login on switch {}'.format(str(host)))) connection.autoinit() specific_version = None logs.append( ('info', 'Using driver {} for host {}'.format(connection.get_driver().name, str(host)))) return (connection, specific_version, logs)
def create_conn(self, connType, devType, host, username, password): if connType == "ssh": account = Account(username, password) ssh = SSH2() try: ssh.connect(host) ssh.set_driver(self.DEV_TYPE.get(devType, " ")) ssh.login(account) except Exception, e: return None return ssh
def __create__(self, host): account = Account(name=USERNAME, password=PASSWORD) self.name = host self.conn = SSH2() if self.conn.connect(host): print('Connected') self.conn.login(account) # self.conn.execute('cli') else: print('Does not connected. Please check your input') sys.exit()
def create_conn(*args, **kwargs): # To read credential from stdin # account = read_login() # account = Account('username', 'password') jump_host = kwargs['jump_host'] account = Account(jump_host['username'], jump_host['password']) conn = SSH2() # This is required for Centos jump_host issue. exscript cannot auto detect os in guess os conn.set_driver('shell') conn.connect(jump_host['ip']) # conn.connect('jump_host.foo.com') conn.login(account) return conn
def verify_switch_ip_dns(self, ip_address, subnet, gateway, dns_server, dns_domain): '''Verify Switch Correctly reports configured IP Address and DNS Input: ip_address: Switch IP address in 1.2.3.4 format subnet: Switch subnet in /18 /24 format gateway IP address of default gateway dns_server dns-server IP address in 1.2.3.4 format dns-domain dns-server IP address in bigswitch.com format ''' try: conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') conn.execute('show running-config interface') run_config = conn.response helpers.log("Running Config O/P: \n %s" % (run_config)) pass_count = 0 input1 = "interface ma1 ip-address " + str(ip_address) + "/" + str( subnet) if input1 in run_config: pass_count = pass_count + 1 input2 = "ip default-gateway " + str(gateway) if input2 in run_config: pass_count = pass_count + 1 input3 = "dns-domain " + str(dns_domain) if input3 in run_config: pass_count = pass_count + 1 input4 = "dns-server " + str(dns_server) if input4 in run_config: pass_count = pass_count + 1 conn.execute('show interface ma1 detail') show_command = conn.response helpers.log("Show Command O/P: \n %s" % (show_command)) if "ma1 is up" in show_command: pass_count = pass_count + 1 input5 = str(ip_address) + "/" + str(subnet) if input5 in show_command: pass_count = pass_count + 1 if "MTU 1500 bytes, Speed 1000 Mbps" in show_command: pass_count = pass_count + 1 if pass_count == 7: return True else: return False except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def __init__(self, address, cred): """Initial a router object :param address: Router address,example:'192.168.10.10' :param cred: Router user and password,example:'vyos:vyos' """ self.__address = address self.__cred = list(cred) self.__divi = self.__cred.index(":") self.__username = ''.join(self.__cred[:self.__divi]) self.__passwd = ''.join(self.__cred[self.__divi+1:]) self.__account = Account(self.__username, self.__passwd) self.__conn = SSH2() self.__status = {"object": None, "commit": None, "save": None, "configure": None}
def snmp_show(self, ip_address): '''Execute CLI command "show snmp-server". Input: ip_address IP Address of switch ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute("show snmp-server") return conn.response except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def verify_switch_dhcp_ip_dns(self, ip_address, subnet, dns_server, dns_domain): '''Verify Switch Correctly reports configured IP Address and DNS ''' try: conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') conn.execute('show running-config interface') run_config = conn.response helpers.log("Running Config O/P: \n %s" % (run_config)) pass_count = 0 input1 = "interface ma1 ip-address dhcp" if input1 in run_config: pass_count = pass_count + 1 input2 = "dns-domain " + str(dns_domain) if input2 in run_config: pass_count = pass_count + 1 input3 = "dns-server " + str(dns_server) if input3 in run_config: pass_count = pass_count + 1 conn.execute('show interface ma1 detail') show_command = conn.response output_1 = string.split(show_command, '\n') output_2 = string.split(output_1[3], ': ') output_3 = string.split(output_2[1], '/') switch_ip = output_3[0] switch_mask = output_3[1] helpers.log("Show Command O/P: \n %s" % (show_command)) if "ma1 is up" in show_command: pass_count = pass_count + 1 input4 = str(ip_address) + "/" + str(subnet) if input4 in show_command: pass_count = pass_count + 1 if "MTU 1500 bytes, Speed 1000 Mbps" in show_command: pass_count = pass_count + 1 if pass_count == 6: return True else: return False except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def activate_deactivate_controller(self, ip_address, iteration): '''Activate and deactivate controller configuration on switch Inputs: ip_address IP Address of Switch iteration Number of times the operation has to be performed ''' try: t = test.Test() c = t.controller() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) mycount = 1 while (mycount <= iteration): conn.execute('enable') conn.execute('conf t') inp = "no controller " + str(c.ip) conn.execute(inp) conn.execute('end') conn.execute('show running-config openflow') print conn.response helpers.sleep(10) conn.execute('conf t') inp = "controller " + str(c.ip) conn.execute(inp) conn.execute('end') conn.execute('show running-config openflow') print conn.response if iteration > mycount: mycount = mycount + 1 helpers.sleep(10) elif mycount == iteration: conn.send('exit\r') conn.send('exit\r') conn.send('exit\r') conn.close() return True except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def do_commands(host, commands_file, account): global error_count global success_count error = 0 try: commands = open(commands_file) except: print "[!] %s - Error opening commands file" % host.rstrip() outfile.write("[!] %s - Error opening commands file" % host.rstrip()) return try: #print "[*] %s - Connecting" % host.rstrip() outfile.write("[*] %s - Connecting\n" % host.rstrip()) conn = SSH2(timeout=10) conn.connect(host.rstrip()) conn.login(account) except: #print "[!] %s - Error connecting" %host.rstrip() outfile.write("[!] %s - Error connecting\n" % host.rstrip()) error_count = error_count + 1 return #print " [-] %s - Starting commands" % host.rstrip() outfile.write(" [-] %s - Starting commands\n" % host.rstrip()) for command in commands: try: conn.execute(command) #print conn.response except: #print "[!] %s - Error: did not finish command %s" % (host.rstrip(),command.rstrip()) outfile.write("[!] %s - Error: did not finish command %s\n" % (host.rstrip(), command.rstrip())) error = 1 outfile.write(" [-] %s - %s complete\n" % (host.rstrip(), command.rstrip())) if error == 1: error_count = error_count + 1 else: success_count = success_count + 1 conn.send('exit\r') #print "[**] %s - Commands complete" % host.rstrip() outfile.write("[**] %s - Commands complete\n" % host.rstrip())
def main(argv): ip = argv[0] username = argv[1] password = argv[2] account = Account(name=username, password=password) #conn = SSH2(debug=5) conn = SSH2() # need this otherwise stupid aruba stuff gets in the way. conn.set_driver('ios') conn.connect(ip) conn.login(account) conn.execute('term len 0') conn.execute('show clock') print conn.response conn.execute('conf t') print conn.response.strip() for cmd in cmds.split("\n"): conn.execute(cmd) print conn.response
def configure_controller(self, ip_address, controller_ip): '''Configure controller IP address on switch Input: ip_address: IP Address of switch ''' t = test.Test() try: conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') conn.execute('conf t') input = "controller " + controller_ip conn.execute(input) helpers.sleep(float(30)) return True except: helpers.test_failure("Configuration delete failed") return False
def configure_portchannel(self, ip_address, pcNumber, portList, hashMode): '''Configure port-channel Inputs: ip_address IP Address of switch pcNumber PortChannel number. Range is between 1 and 30 portList Comma or - separated list of ports (integer values) that are part of PortChannel group. hashMode Hash Mode. Supported values are L2 or L3 Returns: True if configuration is a success or False otherwise Examples: | configure portchannel | 10.192.75.7 | 1 | 49-50 | L3 | ''' try: t = test.Test() conn = SSH2() conn.connect(ip_address) conn.login(Account("admin", "adminadmin")) conn.execute('enable') conn.execute('conf t') input_value = "port-channel " + str( pcNumber) + " interface-list " + str( portList) + " hash " + str(hashMode) helpers.log("Input is %s" % input_value) try: conn.execute(input_value) except: return False return True except: helpers.test_failure( "Could not execute command. Please check log for errors") return False
def Core(self, host_ips, cmdz, timez): print "Core" #archivo_por_nombre = "/NAS_ddos_tools/VNSS_Nocc/.logs/" + usernamee + "_logC_" + d #filename=open(archivo_por_nombre,'a') try: print host_ips conn = SSH2(verify_fingerprint=False) conn.connect(host_ips) conn.login(accountcore) print for h in cmdz: listastring = str(h) conn.execute(listastring) print conn.response print print print #filename.write('\n') #filename.write("*************** \n") #filename.write(timez) #filename.write('\n') #filename.write(host_ips) #filename.write('\n') #filename.write('\n') #filename.write(view_print) #filename.write("*************** \n") #filename.write("*************** \n") time.sleep(2) #filename.close() print print "********************************" print "Hosts CHECKED! +++REGULAR++++" print "********************************" except: print print "IP for this device : ", host_ips print "Incorrect commands or host not available...."
def __init__(self, **kwargs): SSH2.__init__(self, **kwargs) register_drivers(SaegwSSH2Driver()) self.set_driver('saegw_ssh2')
def __init__(self, **kwargs): SSH2.__init__(self, **kwargs) register_drivers(MMESSH2Driver()) self.set_driver('mme_ssh2')