def setUp(self): self.user1 = 'testuser1' self.password1 = 'test1' self.account1 = Account(self.user1, self.password1) self.user2 = 'testuser2' self.password2 = 'test2' self.account2 = Account(self.user2, self.password2) self.accm = AccountPool()
def testConstructor(self): key = PrivateKey() account = Account(self.user, self.password1, key = key) self.assertEqual(account.get_key(), key) self.assertEqual(account.get_password(), account.get_authorization_password()) account = Account(self.user, self.password1, self.password2) self.failIfEqual(account.get_password(), account.get_authorization_password())
def __get_account_from_row(self, row): assert row is not None tbl_a = self._table_map['account'] if row[tbl_a.c.host] is None: return None if row[tbl_a.c.keyfile]: account = Account(row[tbl_a.c.name], key=row[tbl_a.c.keyfile]) else: account = Account(row[tbl_a.c.name]) account.set_password(row[tbl_a.c.password]) account.set_authorization_password(row[tbl_a.c.authorization_password]) #TODO: account.set_skey_password(row[tbl_a.c.skey_password]) return account
def auto_authorize(self, conn, account, flush, bailout): conn.set_timeout(1) conn.send('\r') try: if conn.waitfor( [re.compile(r'[\r\n][\-\w+\.:/]+(?:\([^\)]+\))?[>] ?$')]): conn.set_timeout(15) conn.send('enable' + '\r') conn.app_authorize(Account('admin', 'pass')) conn.app_authorize(Account('admin', 'pass')) except: pass conn.set_timeout(15) self.init_terminal(conn)
def testAddAccountPool(self): self.assertEqual(0, self.accm.default_pool.n_accounts()) account = Account('user', 'test') self.queue.add_account(account) self.assertEqual(1, self.accm.default_pool.n_accounts()) def match_cb(data, host): data['match-called'].value = True return True def start_cb(data, job, host, conn): account = conn.account_factory(None) data['start-called'].value = True data['account-hash'].value = account.__hash__() account.release() # Replace the default pool. pool1 = AccountPool() self.queue.add_account_pool(pool1) self.assertEqual(self.accm.default_pool, pool1) # Add another pool, making sure that it does not replace # the default pool. pool2 = AccountPool() account2 = Account('user', 'test') pool2.add_account(account2) match_called = Value(ctypes.c_bool, False) start_called = Value(ctypes.c_bool, False) account_hash = Value(ctypes.c_long, 0) data = { 'match-called': match_called, 'start-called': start_called, 'account-hash': account_hash } self.queue.add_account_pool(pool2, partial(match_cb, data)) self.assertEqual(self.accm.default_pool, pool1) # Make sure that pool2 is chosen (because the match function # returns True). self.queue.run('dummy://dummy', partial(start_cb, data)) self.queue.shutdown() data = dict((k, v.value) for (k, v) in data.iteritems()) self.assertEqual( data, { 'match-called': True, 'start-called': True, 'account-hash': account2.__hash__() })
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 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 connect(self): acc = Account(self.user, self.password) conn = ssh2.SSH2() conn.connect(self.ip) time.sleep(3) conn.login(acc) return conn
def setUp(self): self.user = '******' self.password1 = 'test1' self.password2 = 'test2' self.key = PrivateKey() self.account = Account(self.user, self.password1, self.password2, self.key)
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 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 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 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 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 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 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 setUp(self): from Exscript import Account from Exscript.util.decorator import bind self.data = Value('i', 0) self.callback = bind(count_calls, self.data, testarg=1) self.account = Account('test', 'test')
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 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 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 verify(): from Exscript import Account from web.widget.connector import MMETelnet, MMESSH2, SaegwTelnet, SaegwSSH2 try: data = request.get_json(True) address = data['host'] account = Account(name=data['user'], password=data['passwd']) port = int(data['port']) type = data['type'] conntype = data['conntype'] conn = None if type == "MME": if conntype == "Telnet": conn = MMETelnet() elif conntype == "SSH": conn = MMESSH2(verify_fingerprint=False) elif type == "SAEGW": if conntype == "Telnet": conn = SaegwTelnet() elif conntype == "SSH": conn = SaegwSSH2(verify_fingerprint=False) if conn == None: raise Exception( "Unsupported NE type [%s] or connection type [%s]." % (type, conntype)) conn.connect(address, port) conn.login(account) conn.logout() conn.close() return jsonify(success=True) except Exception as e: logging.error(e) return jsonify(success=False)
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 add_worker(self, ne, command_list): if len(command_list) is 0: return commands = [] for cmd in command_list: cls = cmd.split("\n") for cl in cls: cl = cl.strip() if len(cl) > 0: commands.append(cl.strip()) conn = None try: account = Account(name=ne.user, password=ne.password) if ne.type == "MME": if ne.conntype == "Telnet": conn = MMETelnet() elif ne.conntype == "SSH": conn = MMESSH2(verify_fingerprint=False) elif ne.type == "SAEGW": if ne.conntype == "Telnet": conn = SaegwTelnet() elif ne.conntype == "SSH": conn = SaegwSSH2(verify_fingerprint=False) if conn == None: raise Exception( "Unsupported NE type [%s] or connection type [%s]." % (ne.type, ne.conntype)) worker = Worker(ne.id, ne.name, ne.type, ne.address, int(ne.port), account, conn, commands, self.result_callback) self.workers_pool.append(worker) except Exception as e: logging.error(e)
def testAuthenticate(self): # Test can not work on the abstract base. if self.protocol.__class__ == Protocol: self.assertRaises(Exception, self.protocol.authenticate, self.account) return self.doConnect() # Password login. self.assertFalse(self.protocol.is_protocol_authenticated()) self.assertFalse(self.protocol.is_app_authenticated()) self.assertFalse(self.protocol.is_app_authorized()) self.protocol.authenticate(self.account, flush=False) self.assertTrue(self.protocol.response is not None) self.assertTrue(len(self.protocol.response) > 0) self.assertTrue(self.protocol.is_protocol_authenticated()) self.assertTrue(self.protocol.is_app_authenticated()) self.assertFalse(self.protocol.is_app_authorized()) # Key login. self.tearDown() self.setUp() key = PrivateKey.from_file('foo', keytype='rsa') account = Account(self.user, self.password, key=key) self.doConnect() self.assertFalse(self.protocol.is_protocol_authenticated()) self.assertFalse(self.protocol.is_app_authenticated()) self.assertFalse(self.protocol.is_app_authorized()) self.protocol.authenticate(account, flush=False) self.assertTrue(self.protocol.is_protocol_authenticated()) self.assertTrue(self.protocol.is_app_authenticated()) self.assertFalse(self.protocol.is_app_authorized())
def get_accounts_from_file(filename): """ Reads a list of user/password combinations from the given file and returns a list of Account instances. The file content has the following format:: [account-pool] user1 = cGFzc3dvcmQ= user2 = cGFzc3dvcmQ= Note that "cGFzc3dvcmQ=" is a base64 encoded password. If the input file contains extra config sections other than "account-pool", they are ignored. Each password needs to be base64 encrypted. To encrypt a password, you may use the following command:: python -c 'import base64; print base64.b64encode("thepassword")' :type filename: string :param filename: The name of the file containing the list of accounts. :rtype: list[Account] :return: The newly created account instances. """ accounts = [] cfgparser = __import__('ConfigParser', {}, {}, ['']) parser = cfgparser.RawConfigParser() parser.optionxform = str parser.read(filename) for user, password in parser.items('account-pool'): accounts.append(Account(user, base64.decodestring(password))) return accounts
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 __enter__(self): self.account = Account(JUNIPER_ROUTER_TELNET_USER, password=JUNIPER_ROUTER_TELNET_PASS) self.conn = Telnet(debug=TELNET_DEBUG_LEVEL, connect_timeout=None) self.conn.connect(self.host_address) self.conn.set_driver(JunOSDriver()) self.conn.login(self.account) return self
def __enter__(self): self.account = Account(self.telnet_username, password=self.telnet_password) self.conn = Telnet(debug=TELNET_DEBUG_LEVEL, connect_timeout=PYCURL_TIMEOUT) self.conn.connect(self.host_address, port=self.port) self.conn.set_driver(self.exscript_driver()) self.conn.login(self.account) return self
def read_login(): """ Like get_login(), but returns an Account object. @rtype: Account @return: A new account. """ user, password = get_login() return Account(user, password)