Ejemplo n.º 1
0
    def __init__(self, crb, serializer, name, alt_session=True, dut_id=0):
        self.dut_id = dut_id
        self.crb = crb
        self.read_cache = False
        self.skip_setup = False
        self.serializer = serializer
        self.ports_info = None
        self.sessions = []
        self.stage = 'pre-init'
        self.name = name

        self.logger = getLogger(name)
        self.session = SSHConnection(self.get_ip_address(), name,
                                     self.get_username(),
                                     self.get_password(), dut_id)
        self.session.init_log(self.logger)
        if alt_session:
            self.alt_session = SSHConnection(
                self.get_ip_address(),
                name + '_alt',
                self.get_username(),
                self.get_password(),
                dut_id)
            self.alt_session.init_log(self.logger)
        else:
            self.alt_session = None
Ejemplo n.º 2
0
    def reconnect_session(self, alt_session=False):
        """
        When session can't used anymore, recreate another one for replace
        """
        try:
            if alt_session:
                self.alt_session.close(force=True)
            else:
                self.session.close(force=True)
        except Exception as e:
            self.loggger.error("Session close failed for [%s]" % e)

        if alt_session:
            session = SSHConnection(
                self.get_ip_address(),
                self.name + '_alt',
                self.get_username(),
                self.get_password())
            self.alt_session = session
        else:
            session = SSHConnection(self.get_ip_address(), self.name,
                                    self.get_username(), self.get_password())
            self.session = session

        session.init_log(self.logger)
Ejemplo n.º 3
0
 def __init__(self, crb, serializer, name):
     self.crb = crb
     self.skip_setup = False
     self.serializer = serializer
     self.ports_info = None
     self.sessions = []
     self.name = name
     self.logger = getLogger(name)
     self.session = SSHConnection(self.get_ip_address(), name,
                                  self.get_password())
     self.session.init_log(self.logger)
     self.alt_session = SSHConnection(self.get_ip_address(), name + '_alt',
                                      self.get_password())
     self.alt_session.init_log(self.logger)
Ejemplo n.º 4
0
def main(argv):
  # Parse the username, hostname, and keyfile from the command line arguments
  username, hostname = argv[1].split('@')
  keyfile = argv[2]

  # Construct an SSH connection
  ssh = SSHConnection(hostname, username, keyfile)
  ssh.connect()

  # Run an interactive prompt, until the user enters an empty line or closes the input stream
  print colors.red(ssh.read())
  while True:
    try:
      command_to_run = raw_input('> ')
    except EOFError:
      command_to_run = ''

    if command_to_run.strip() == '':
      break
    ssh.send(command_to_run + '\n')
    print colors.red(ssh.read())

  # Cleanly close the SSH connection
  exit_status = ssh.disconnect()
  return exit_status
Ejemplo n.º 5
0
def process_logs(info):
    from ssh_connection import SSHConnection
    import re

    for host, host_info in info.items():
        with SSHConnection(host, host_info["username"],
                           host_info["password"]) as conn:
            if "logfiles" in host_info:
                for path, regex in host_info["logfiles"]:
                    pattern = re.compile(regex)
                    with conn.open(path) as infile:
                        for line in infile:
                            matches = pattern.finditer(line)
                            if matches:
                                for m in matches:
                                    yield m

            if "logcommands" in host_info:
                for command, regex in host_info["logcommands"]:
                    pattern = re.compile(regex)
                    _, stdout, _ = conn.exec_command(command)
                    for line in stdout:
                        matches = pattern.finditer(line)
                        if matches:
                            for m in matches:
                                yield m
Ejemplo n.º 6
0
    def createConnection(self):
        """ Method to create connection

        @return httplib connection object
        """

        conn = ""
        context = ssl._create_unverified_context()
        if self.type == "https":
            conn = httplib.HTTPSConnection(self.ip, context=context)
            sock = socket.create_connection((conn.host, conn.port),
                                            conn.timeout, conn.source_address)
            conn.sock = ssl.wrap_socket(sock,
                                        conn.key_file,
                                        conn.cert_file,
                                        ssl_version=ssl.PROTOCOL_TLSv1)
        elif self.type == "ssh":
            conn = SSHConnection(self.ip, self.username, self.password)
        elif self.type == "scp":
            transport = paramiko.Transport((self.ip, 22))
            transport.connect(username="******", password=self.password)
            conn = paramiko.SFTPClient.from_transport(transport)
        elif self.type == "expect":
            conn = ExpectConnection(self.ip, self.username, self.password)
        else:
            conn = httplib.HTTPConnection(self.ip)
        return conn
Ejemplo n.º 7
0
def _stop_project(ssh_host: str, ssh_user: str, ssh_password: str,
                  project_name: str) -> None:
    logging.info(f"[{ssh_host}] Stopping project")

    ssh: SSHConnection = SSHConnection(ssh_host, ssh_user, ssh_password)

    ssh.execute(f"screen -X -S {project_name} quit")

    ssh.close()
Ejemplo n.º 8
0
 def __init__(self, crb, serializer):
     super(Dut, self).__init__(crb, serializer)
     self.NAME = 'dut'
     self.logger = getLogger(self.NAME)
     self.session = SSHConnection(self.get_ip_address(), self.NAME,
                                  self.get_password())
     self.session.init_log(self.logger)
     self.alt_session = SSHConnection(self.get_ip_address(),
                                      self.NAME + '_alt',
                                      self.get_password())
     self.alt_session.init_log(self.logger)
     self.number_of_cores = 0
     self.tester = None
     self.cores = []
     self.architecture = None
     self.ports_info = None
     self.conf = UserConf()
     self.ports_map = []
Ejemplo n.º 9
0
 def init_host_session(self):
     if self.host_init_flag:
         pass
     else:
         self.host_session = SSHConnection(self.get_ip_address(),
                                           self.NAME + '_host',
                                           self.get_password())
         self.host_session.init_log(self.logger)
         self.host_init_flag = True
Ejemplo n.º 10
0
 def create_session(self, name=""):
     """
     Create new session for addtional useage. This session will not enable log.
     """
     logger = getLogger(name)
     session = SSHConnection(self.get_ip_address(), name,
                             self.get_username(), self.get_password())
     session.init_log(logger)
     self.sessions.append(session)
     return session
Ejemplo n.º 11
0
 def init_host_session(self, vm_name):
     """
     Create session for each VM, session will be handled by VM instance
     """
     self.host_session = SSHConnection(self.get_ip_address(),
                                       vm_name + '_host',
                                       self.get_username(),
                                       self.get_password())
     self.host_session.init_log(self.logger)
     self.logger.info("[%s] create new session for VM" %
                      (threading.current_thread().name))
    def __init__(self, config_path: Path, experiment_path: Path,
                 skip_list: List[str], ssh_password: str, node_index: int):
        self.config: Configuration = Configuration.load(config_path)
        self.experiment: Experiment = Experiment.load(experiment_path)
        self._node_index: int = node_index
        self.node: str = self.config.nodes[node_index]
        self.skip_list: List[str] = skip_list
        self.ssh_password: str = ssh_password
        self.command: str = ExperimentEnvironment(self.config, self.experiment,
                                                  node_index).command

        self.ssh: SSHConnection = SSHConnection(self.node,
                                                self.config.ssh_user,
                                                ssh_password)
def process_server(host, info, out):
    from ssh_connection import SSHConnection
    with SSHConnection(host, info["username"], info["password"]) as ssh:
        parse_logfiles(ssh.sftp_client, host, info, out)
Ejemplo n.º 14
0
        uuid_set_list.append(uuid_set)

    uuid_set_str = ','.join(uuid_set_list)
    update_cmd = update_template % {'uuid': uuid_set_str, 'name': port}

    cmd_list.append(update_cmd)
    cmd_str = ','.join(cmd_list)

    cmd = "ovsdb-client transact '[\"Open_vSwitch\", %s]'" % cmd_str
    ssh.send_expect(cmd, '# ')


if __name__ == "__main__":
    from ssh_connection import SSHConnection

    ssh = SSHConnection('192.168.8.103', 'root', '111111')
    all_intf_uuid = get_ovs_all_interface_uuid(ssh)
    print "All interface uuids: ", all_intf_uuid
    ports = get_ovs_port_interface_uuid(ssh, 'bond0')
    print "ports uuid are: ", ports
    add_interface_to_port(ssh, 'bond0', *['eth1'])
    interfaces = ssh.send_expect(
        "ovsdb-client transact '[\"Open_vSwitch\", {\"op\":\"select\", \"table\":\"Interface\", \"columns\":[\"name\"], \"where\":[]}]'",
        '# ')
    print "Now interfaces: ", interfaces
    remove_interface_to_port(ssh, 'bond0', *['eth1'])
    interfaces = ssh.send_expect(
        "ovsdb-client transact '[\"Open_vSwitch\", {\"op\":\"select\", \"table\":\"Interface\", \"columns\":[\"name\"], \"where\":[]}]'",
        '# ')
    print "Now interfaces: ", interfaces
Ejemplo n.º 15
0
from ssh_connection import SSHConnection

with SSHConnection("192.168.56.101", "root", "welcome") as conn:
    conn.put("a.py", "/tmp/a.py")
    conn.chmod("/tmp/a.py", 0o755)
    stdin, stdout, stderr = conn.exec_command("/tmp/a.py")
    print(str(stdout.read(), "utf8"))
    conn.get("/etc/passwd", "localfile.txt")