Esempio n. 1
0
 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()
Esempio n. 2
0
 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)
Esempio n. 3
0
    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 list(data.items()))
        self.assertEqual(data, {'match-called': True,
                                'start-called': True,
                                'account-hash': account2.__hash__()})
Esempio n. 4
0
    def __init__(self, parent, account=None, show_authorization=False):
        """
        A simple login widget with a username and password field.

        @type  parent: tkinter.Frame
        @param parent: The parent widget.
        @type  account: Exscript.Account
        @param account: An optional account that is edited.
        @type  show_authorization: bool
        @param show_authorization: Whether to show the "Authorization" entry.
        """
        Frame.__init__(self, parent)
        self.pack(expand=True, fill=BOTH)
        self.columnconfigure(0, pad=6)
        self.columnconfigure(1, weight=1)
        row = -1

        # Username field.
        self.label_user = Label(self, text='User:'******'<Key>', self._on_field_changed)

        # Password field.
        self.label_password1 = Label(self, text='Password:'******'*')
        row += 1
        self.rowconfigure(row, pad=row > 0 and 6 or 0)
        self.label_password1.grid(row=row, column=0, sticky=W)
        self.entry_password1.grid(row=row,
                                  column=1,
                                  columnspan=2,
                                  sticky=W + E)
        self.entry_password1.bind('<Key>', self._on_field_changed)

        # Authorization password field.
        self.label_password2 = Label(self, text='Authorization:')
        self.entry_password2 = Entry(self, show='*')
        if show_authorization:
            row += 1
            self.rowconfigure(row, pad=row > 0 and 6 or 0)
            self.label_password2.grid(row=row, column=0, sticky=W)
            self.entry_password2.grid(row=row,
                                      column=1,
                                      columnspan=2,
                                      sticky=W + E)
            self.entry_password2.bind('<Key>', self._on_field_changed)

        self.locked = False
        self.account = None
        self.attach(account and account or Account())
Esempio n. 5
0
    def testReleaseAccounts(self):
        account1 = Account('foo')
        account2 = Account('bar')
        pool = AccountPool()
        pool.add_account(account1)
        pool.add_account(account2)
        pool.acquire_account(account1, 'one')
        pool.acquire_account(account2, 'two')

        self.assert_(account1 not in pool.unlocked_accounts)
        self.assert_(account2 not in pool.unlocked_accounts)
        pool.release_accounts('one')
        self.assert_(account1 in pool.unlocked_accounts)
        self.assert_(account2 not in pool.unlocked_accounts)
        pool.release_accounts('one')
        self.assert_(account1 in pool.unlocked_accounts)
        self.assert_(account2 not in pool.unlocked_accounts)
        pool.release_accounts('two')
        self.assert_(account1 in pool.unlocked_accounts)
        self.assert_(account2 in pool.unlocked_accounts)
Esempio n. 6
0
 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()
Esempio n. 7
0
 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
Esempio n. 8
0
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)
Esempio n. 9
0
    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.assertNotEqual(account.get_password(),
                            account.get_authorization_password())
Esempio n. 10
0
    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
Esempio n. 11
0
 def testCreatePipe(self):
     account = Account('user', 'test')
     self.accm.add_account(account)
     pipe = self.queue._create_pipe()
     pipe.send(('acquire-account', None))
     response = pipe.recv()
     expected = (account.__hash__(), account.get_name(),
                 account.get_password(),
                 account.get_authorization_password(), account.get_key())
     self.assertEqual(response, expected)
     pipe.send(('release-account', account.__hash__()))
     response = pipe.recv()
     self.assertEqual(response, 'ok')
     pipe.close()
Esempio n. 12
0
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
Esempio n. 13
0
 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
Esempio n. 14
0
    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}
Esempio n. 15
0
    def setUp(self):
        self.hostname = '127.0.0.1'
        self.port = 1236
        self.user = '******'
        self.password = '******'
        self.account = Account(self.user, password=self.password)
        self.daemon = None

        self.createVirtualDevice()
        self.createDaemon()
        if self.daemon is not None:
            self.daemon.start()
            time.sleep(.2)
        self.createProtocol()
Esempio n. 16
0
def account_factory(username=getuser(), password=None, private_key="", keytype="rsa"):
    assert username != ""
    assert keytype in set(["rsa", "dsa", "ecdsa", "ed25519"])

    if password is None:
        password = getpass("Login password for %s: " % username)

    private_key_obj = None
    if isinstance(private_key, str) and private_key != "":
        keypath = os.path.expanduser(private_key)
        assert os.path.isfile(keypath)
        private_key_obj = PrivateKey(keytype=keytype).from_file(keypath)

    account = Account(name=username, password=password, key=private_key_obj)
    return account
Esempio n. 17
0
    def connect(self):
        self.errors = []
        try:
            acc = Account(self.user, self.password)
            conn = ssh2.SSH2()
            conn.connect(self.ip)
            conn.login(acc)
            conn.set_timeout(60)
            return conn

        except Exception as e:
            self.errors.append('Error')
            for i in e:
                self.errors.append(i)

            return self.errors
Esempio n. 18
0
 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
Esempio n. 19
0
 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
Esempio n. 20
0
 def testCreatePipe(self):
     account = Account('user', 'test')
     self.accm.add_account(account)
     pipe = self.queue._create_pipe()
     pipe.send(('acquire-account', None))
     response = pipe.recv()
     expected = (account.__hash__(),
                 account.get_name(),
                 account.get_password(),
                 account.get_authorization_password(),
                 account.get_key())
     self.assertEqual(response, expected)
     pipe.send(('release-account', account.__hash__()))
     response = pipe.recv()
     self.assertEqual(response, 'ok')
     pipe.close()
Esempio n. 21
0
    def testStart(self):
        # Test can not work on the abstract base.
        if self.daemon.__class__ == Server:
            return
        self._create_daemon()
        self._add_commands()
        self.daemon.start()
        time.sleep(1)

        client = self._create_client()
        client.set_prompt(re.compile(r'\w+:\d+> ?'))
        client.connect(self.host, self.port)
        client.login(Account('user', 'password'))
        client.execute('ls')
        self.assertEqual(client.response, 'ok1\n')
        client.execute('ll')
        self.assertEqual(client.response, 'ok2\n')
        client.send('exit\r')
Esempio n. 22
0
def authorize(scope, password=[None]):
    """
    Looks for a password prompt on the current connection
    and enters the given password.
    If a password is not given, the function uses the same
    password that was used at the last login attempt; it is
    an error if no such attempt was made before.

    :type  password: string
    :param password: A password.
    """
    conn = scope.get('__connection__')
    password = password[0]
    if password is None:
        conn.app_authorize()
    else:
        account = Account('', password)
        conn.app_authorize(account)
    return True
Esempio n. 23
0
    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
Esempio n. 24
0
def main(thread_count, logfile, hosts_file, commands_file, username, password):
    global outfile
    global count
    global host_count
    global error_count
    global success_count

    count = 0
    host_count = 0
    error_count = 0
    success_count = 0
    hosts = open(hosts_file)
    outfile = open(logfile, 'w')
    commands = open(commands_file)
    account = Account(username, password)

    print "[*] Starting sshNAS..."
    outfile.write("Starting sshNAS...\n")
    q = Queue.Queue()
    for host in hosts:
        q.put(host)
        host_count = host_count + 1

    threads = []
    for i in range(thread_count):
        t = threading.Thread(target=worker,
                             args=(
                                 q,
                                 commands_file,
                                 account,
                                 thread_count,
                             ))
        threads.append(t)

    # Start all threads
    [x.start() for x in threads]
    # Wait for all threads to finish before moving on
    [x.join() for x in threads]

    print "[*] Completed (%s\%s)\n\tSuccessful (%s\%s)\n\tFailed (%s\%s)" % (
        count, host_count, success_count, host_count, error_count, host_count)
    print "[*] sshNAS complete!"
Esempio n. 25
0
 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
Esempio n. 26
0
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
Esempio n. 27
0
 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
Esempio n. 28
0
def authenticate_user(scope, user=[None], password=[None]):
    """
    Like authenticate(), but logs in using the given user and password.
    If a user and password are not given, the function uses the same
    user and password that were used at the last login attempt; it is
    an error if no such attempt was made before.

    :type  user: string
    :param user: A username.
    :type  password: string
    :param password: A password.
    """
    conn = scope.get('__connection__')
    user = user[0]
    if user is None:
        conn.app_authenticate()
    else:
        account = Account(user, password[0])
        conn.app_authenticate(account)
    return True
Esempio n. 29
0
 def verify_portchannel_member_state(self, ip_address, pc_number,
                                     intf_name):
     '''Verify if portchannel member interface is up
     
         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 up, 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)
                 if len(intfName) > 1 and intfName[1] == intf_name:
                     if intfName[0] == "*":
                         helpers.log("Intf Name is %s and state is %s \n" %
                                     (intfName[1], intfName[0]))
                         return True
                     else:
                         helpers.log("Intf Name is %s and state is %s \n" %
                                     (intfName[1], intfName[0]))
                         return False
         return False
     except:
         helpers.test_failure(
             "Could not execute command. Please check log for errors")
         return False
Esempio n. 30
0
def auto_authorize(scope, password=[None]):
    """
    Executes a command on the remote host that causes an authorization
    procedure to be started, then authorizes using the given password
    in the same way in which authorize() works.
    Depending on the detected operating system of the remote host the
    following commands are started:

      - on IOS, the "enable" command is executed.
      - nothing on other operating systems yet.

    :type  password: string
    :param password: A password.
    """
    conn = scope.get('__connection__')
    password = password[0]
    if password is None:
        conn.auto_app_authorize()
    else:
        account = Account('', password)
        conn.auto_app_authorize(account)
    return True
Esempio n. 31
0
    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
Esempio n. 32
0
 def verify_controller(self, ip_address, controller_ip, controller_role):
     '''Configure controller IP address on switch
     
         Input:
             ip_address:        IP Address of switch
     '''
     try:
         t = test.Test()
         conn = SSH2()
         conn.connect(ip_address)
         conn.login(Account("admin", "adminadmin"))
         conn.execute('enable')
         input1 = "show running-config openflow"
         conn.execute(input1)
         run_config = conn.response
         helpers.log("Running Config O/P: \n %s" % (run_config))
         input2 = "show controller"
         conn.execute(input2)
         show_output = conn.response
         helpers.log("Show Controllers O/P: \n %s" % (show_output))
         pass_count = 0
         if str(controller_ip) in run_config:
             pass_count = pass_count + 1
         input3 = str(controller_ip) + ":6653"
         if input3 in show_output:
             pass_count = pass_count + 1
         if "CONNECTED" in show_output:
             pass_count = pass_count + 1
         if controller_role in show_output:
             pass_count = pass_count + 1
         if pass_count == 4:
             return True
         else:
             return False
     except:
         helpers.test_failure(
             "Could not execute command. Please check log for errors")
         return False
Esempio n. 33
0
 def delete_snmp_host(self, ip_address, remHostIP, snmpKey, snmpCommunity,
                      snmpPort):
     ''' Delete Remote SNMP Host
     
         Input: 
             ip_address        IP Address of switch
             
             remHostIP         IP Address of remote host
                    
             snmpKey           Acceptable values are traps/informs
             
             snmpCommunity     SNMP community
             
             snmpPort          Port on which traps are sent out.
     '''
     try:
         t = test.Test()
         conn = SSH2()
         conn.connect(ip_address)
         conn.login(Account("admin", "adminadmin"))
         conn.execute('enable')
         conn.execute('conf t')
         if snmpKey == "traps" or snmpKey == "trap":
             snmpKey == "traps"
         else:
             snmpKey == "informs"
         input = "no snmp-server host %s %s %s udp-port %s" % (str(
             remHostIP), str(snmpKey), str(snmpCommunity), str(snmpPort))
         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
Esempio n. 34
0
 def disable_switch_snmp(self, ip_address):
     ''' Disable 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('enable')
         conn.execute('conf t')
         conn.execute("no snmp-server enable")
         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
Esempio n. 35
0
    def restart_process_controller(self, process_name, controllerRole):
        '''Restart a process on controller

            Input:
               processName        Name of process to be restarted
               controllerRole        Where to execute the command. Accepted values are `Master` and `Slave`
        '''
        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')
        input = 'service ' + str(process_name) + ' restart'
        conn.execute(input)
        conn.send('logout\r')
        conn.send('logout\r')
        conn.close()
        return True
Esempio n. 36
0
def showrun(ip, user, password):

    dateformat = '%d%m%y'
    timeformat = '%H%M%S'
    if not os.path.isdir(ip):
        os.makedirs(ip)
    savepath = './' + ip + "/"

    account = Account(user, password)
    conn = SSH2()
    conn.connect(ip)
    conn.login(account)
    conn.execute('terminal length 0')

    conn.execute('show tech-support')
    shrun = conn.response
    s01 = open(
        savepath + "config-" + time.strftime(dateformat) + "-" +
        time.strftime(timeformat) + ".txt", "w")
    s01.write(shrun)
    s01.close()

    conn.send('exit\r')
    conn.close()
Esempio n. 37
0
class AccountTest(unittest.TestCase):
    CORRELATE = Account

    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 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.assertNotEqual(account.get_password(),
                            account.get_authorization_password())

    def testContext(self):
        with self.account as account:
            account.release()
            account.acquire()

        self.account.acquire()
        with self.account.context() as context:
            context.release()
            context.acquire()
            with context.context() as subcontext:
                subcontext.release()
                subcontext.acquire()
                with subcontext.context() as subsubcontext:
                    subsubcontext.release()
                    subsubcontext.acquire()

        with self.account:
            pass

    def testAcquire(self):
        self.account.acquire()
        self.account.release()
        self.account.acquire()
        self.account.release()

    def testRelease(self):
        self.assertRaises(Exception, self.account.release)

    def testSetName(self):
        self.assertEqual(self.user, self.account.get_name())
        self.account.set_name('foo')
        self.assertEqual('foo', self.account.get_name())

    def testGetName(self):
        self.assertEqual(self.user, self.account.get_name())

    def testSetPassword(self):
        self.assertEqual(self.password1, self.account.get_password())
        self.account.set_password('foo')
        self.assertEqual('foo', self.account.get_password())

    def testGetPassword(self):
        self.assertEqual(self.password1, self.account.get_password())

    def testSetAuthorizationPassword(self):
        self.assertEqual(self.password2,
                         self.account.get_authorization_password())
        self.account.set_authorization_password('foo')
        self.assertEqual('foo', self.account.get_authorization_password())

    def testGetAuthorizationPassword(self):
        self.assertEqual(self.password2,
                         self.account.get_authorization_password())

    def testGetKey(self):
        self.assertEqual(self.key, self.account.get_key())
Esempio n. 38
0
 def testGetAccountFromHash(self):
     account = Account('user', 'test')
     thehash = account.__hash__()
     self.accm.add_account(account)
     self.assertEqual(self.accm.get_account_from_hash(thehash), account)
Esempio n. 39
0
class AccountPoolTest(unittest.TestCase):
    CORRELATE = AccountPool

    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):
        accm = AccountPool()
        self.assertEqual(accm.n_accounts(), 0)

        accm = AccountPool([self.account1, self.account2])
        self.assertEqual(accm.n_accounts(), 2)

    def testAddAccount(self):
        self.assertEqual(self.accm.n_accounts(), 0)
        self.accm.add_account(self.account1)
        self.assertEqual(self.accm.n_accounts(), 1)

        self.accm.add_account(self.account2)
        self.assertEqual(self.accm.n_accounts(), 2)

    def testReset(self):
        self.testAddAccount()
        self.accm.reset()
        self.assertEqual(self.accm.n_accounts(), 0)

    def testHasAccount(self):
        self.assertEqual(self.accm.has_account(self.account1), False)
        self.accm.add_account(self.account1)
        self.assertEqual(self.accm.has_account(self.account1), True)

    def testGetAccountFromHash(self):
        account = Account('user', 'test')
        thehash = account.__hash__()
        self.accm.add_account(account)
        self.assertEqual(self.accm.get_account_from_hash(thehash), account)

    def testGetAccountFromName(self):
        self.testAddAccount()
        self.assertEqual(self.account2,
                         self.accm.get_account_from_name(self.user2))

    def testNAccounts(self):
        self.testAddAccount()

    def testAcquireAccount(self):
        self.testAddAccount()
        self.accm.acquire_account(self.account1)
        self.account1.release()
        self.accm.acquire_account(self.account1)
        self.account1.release()

        # Add three more accounts.
        filename = os.path.join(os.path.dirname(__file__), 'account_pool.cfg')
        self.accm.add_account(get_accounts_from_file(filename))
        self.assertEqual(self.accm.n_accounts(), 5)

        for i in range(0, 2000):
            # Each time an account is acquired a different one should be
            # returned.
            acquired = {}
            for n in range(0, 5):
                account = self.accm.acquire_account()
                self.assertTrue(account is not None)
                self.assertNotIn(account.get_name(), acquired)
                acquired[account.get_name()] = account

            # Release one account.
            acquired['abc'].release()

            # Acquire one account.
            account = self.accm.acquire_account()
            self.assertEqual(account.get_name(), 'abc')

            # Release all accounts.
            for account in list(acquired.values()):
                account.release()

    def testReleaseAccounts(self):
        account1 = Account('foo')
        account2 = Account('bar')
        pool = AccountPool()
        pool.add_account(account1)
        pool.add_account(account2)
        pool.acquire_account(account1, 'one')
        pool.acquire_account(account2, 'two')

        self.assertNotIn(account1, pool.unlocked_accounts)
        self.assertNotIn(account2, pool.unlocked_accounts)
        pool.release_accounts('one')
        self.assertIn(account1, pool.unlocked_accounts)
        self.assertNotIn(account2, pool.unlocked_accounts)
        pool.release_accounts('one')
        self.assertIn(account1, pool.unlocked_accounts)
        self.assertNotIn(account2, pool.unlocked_accounts)
        pool.release_accounts('two')
        self.assertIn(account1, pool.unlocked_accounts)
        self.assertIn(account2, pool.unlocked_accounts)