def setup_remote_ssh_key(hostname1, user1, password1, hostname2=None, user2=None, password2=None, port=22): ''' Setup up remote to remote login in another server by using public key If hostname2 is not supplied, setup to local. :param hostname1: the server wants to login other host :param hostname2: the server to be logged in :type hostname: str :param user: user to login :type user: str :param password: password :type password: str :param port: port number :type port: int ''' logging.debug('Performing SSH key setup on %s:%d as %s.' % (hostname1, port, user1)) try: session1 = remote.remote_login(client='ssh', host=hostname1, port=port, username=user1, password=password1, prompt=r'[$#%]') public_key = get_remote_public_key(session1) if hostname2 is None: # Simply create a session to local session2 = aexpect.ShellSession("sh", linesep='\n', prompt='#') else: session2 = remote.remote_login(client='ssh', host=hostname2, port=port, username=user2, password=password2, prompt=r'[$#%]') session2.cmd_output('mkdir -p ~/.ssh') session2.cmd_output('chmod 700 ~/.ssh') session2.cmd_output("echo '%s' >> ~/.ssh/authorized_keys; " % public_key) session2.cmd_output('chmod 600 ~/.ssh/authorized_keys') logging.debug('SSH key setup on %s complete.', session2) except Exception as err: logging.debug('SSH key setup has failed: %s', err) try: session1.close() session2.close() except Exception: pass
def setup_ssh_key(hostname, user, password, port=22): ''' Setup up remote login in another server by using public key :param hostname: the server to login :type hostname: str :param user: user to login :type user: str :param password: password :type password: str :param port: port number :type port: int ''' logging.debug('Performing SSH key setup on %s:%d as %s.' % (hostname, port, user)) try: public_key = get_public_key() session = remote.remote_login(client='ssh', host=hostname, port=port, username=user, password=password, prompt=r'[$#%]') session.cmd_output('mkdir -p ~/.ssh') session.cmd_output('chmod 700 ~/.ssh') session.cmd_output("echo '%s' >> ~/.ssh/authorized_keys; " % public_key) session.cmd_output('chmod 600 ~/.ssh/authorized_keys') logging.debug('SSH key setup complete.') except Exception as err: logging.debug('SSH key setup has failed: %s', err) try: session.close() except: pass
def login(self, nic_index=0, timeout=LOGIN_TIMEOUT, username=None, password=None): """ Log into the guest via SSH/Telnet/Netcat. If timeout expires while waiting for output from the guest (e.g. a password prompt or a shell prompt) -- fail. :param nic_index: The index of the NIC to connect to. :param timeout: Time (seconds) before giving up logging into the guest. :return: A ShellSession object. """ error.context("logging into '%s'" % self.name) if not username: username = self.params.get("username", "") if not password: password = self.params.get("password", "") prompt = self.params.get("shell_prompt", "[\#\$]") linesep = eval("'%s'" % self.params.get("shell_linesep", r"\n")) client = self.params.get("shell_client") address = self.get_address(nic_index) port = self.get_port(int(self.params.get("shell_port"))) log_filename = ("session-%s-%s.log" % (self.name, utils_misc.generate_random_string(4))) session = remote.remote_login(client, address, port, username, password, prompt, linesep, log_filename, timeout) session.set_status_test_command( self.params.get("status_test_command", "")) self.remote_sessions.append(session) return session
def start_ip_sniffing(self, params): """ Start ip sniffing. :param params: Params object. """ self.data.setdefault("address_cache", ip_sniffing.AddrCache()) sniffers = ip_sniffing.Sniffers if not self._sniffer: remote_pp = params.get("remote_preprocess") == "yes" remote_opts = None session = None if remote_pp: client = params.get('remote_shell_client', 'ssh') remote_opts = (params['remote_node_address'], params.get('remote_shell_port', '22'), params['remote_node_user'], params['remote_node_password'], params.get('remote_shell_prompt', '#')) session = remote.remote_login(client, *remote_opts) for s_cls in sniffers: if s_cls.is_supported(session): self._sniffer = s_cls(self.data["address_cache"], "ip-sniffer.log", remote_opts) break if session: session.close() if not self._sniffer: raise exceptions.TestError("Can't find any supported ip sniffer! " "%s" % [s.command for s in sniffers]) self._sniffer.start()
def __init__(self, address, netperf_path, md5sum="", netperf_source="", client="ssh", port="22", username="******", password="******", compile_option="--enable-demo=yes", install=True): """ Init NetperfServer class. :param address: Remote host or guest address :param netperf_path: Remote netperf path :param me5sum: Local netperf package me5sum :param netperf_source: netperf source file (path or link) which will transfer to remote :param client: The client to use ('ssh', 'telnet' or 'nc') :param port: Port to connect to :param username: Username (if required) :param password: Password (if required) """ self.client = client if client == "nc": self.prompt = r"^\w:\\.*>\s*$" self.linesep = "\r\n" else: self.prompt = "^\[.*\][\#\$]\s*$" self.linesep = "\n" self.package = NetperfPackage(address, netperf_path, md5sum, netperf_source, client, port, username, password) self.netserver_path, self.netperf_path = self.package.install(install, compile_option) logging.debug("Create remote session") self.session = remote.remote_login(client, address, port, username, password, self.prompt, self.linesep, timeout=360)
def login(self, nic_index=0, timeout=LOGIN_TIMEOUT, username=None, password=None): """ Log into the guest via SSH/Telnet/Netcat. If timeout expires while waiting for output from the guest (e.g. a password prompt or a shell prompt) -- fail. @param nic_index: The index of the NIC to connect to. @param timeout: Time (seconds) before giving up logging into the guest. @return: A ShellSession object. """ error.context("logging into '%s'" % self.name) if not username: username = self.params.get("username", "") if not password: password = self.params.get("password", "") prompt = self.params.get("shell_prompt", "[\#\$]") linesep = eval("'%s'" % self.params.get("shell_linesep", r"\n")) client = self.params.get("shell_client") address = self.get_address(nic_index) port = self.get_port(int(self.params.get("shell_port"))) log_filename = ("session-%s-%s.log" % (self.name, utils_misc.generate_random_string(4))) session = remote.remote_login(client, address, port, username, password, prompt, linesep, log_filename, timeout) session.set_status_test_command(self.params.get("status_test_command", "")) self.remote_sessions.append(session) return session
def __init__(self, address, netperf_path, md5sum="", netperf_source="", client="ssh", port="22", username="******", password="******"): """ Class NetperfPackage just represent the netperf package Init NetperfPackage class. :param address: Remote host or guest address :param netperf_path: Installed netperf path :param me5sum: Local netperf package me5sum :param netperf_source: source netperf (path or link) path :param client: The client to use ('ssh', 'telnet' or 'nc') :param port: Port to connect to :param username: Username (if required) :param password: Password (if required) """ super(NetperfPackage, self).__init__(address, client, username, password, port, netperf_path) self.netperf_source = netperf_source self.pack_suffix = "" self.netperf_dir = None self.build_tool = False self.md5sum = md5sum self.netperf_base_dir = self.remote_path self.netperf_file = os.path.basename(self.netperf_source) if client == "nc": self.prompt = r"^\w:\\.*>\s*$" self.linesep = "\r\n" self.status_test_command = "echo %errorlevel%" else: self.prompt = "^\[.*\][\#\$]\s*$" self.linesep = "\n" self.status_test_command = "echo $?" if self.netperf_source.endswith("tar.bz2"): self.pack_suffix = ".tar.bz2" self.decomp_cmd = "tar jxvf" elif self.netperf_source.endswith("tar.gz"): self.pack_suffix = ".tar.gz" self.decomp_cmd = "tar zxvf" self.netperf_dir = os.path.join(self.remote_path, self.netperf_file.rstrip(self.pack_suffix)) if self.pack_suffix: self.netserver_path = os.path.join(self.netperf_dir, "src/netserver") self.netperf_path = os.path.join(self.netperf_dir, "src/netperf") else: self.netserver_path = os.path.join(self.netperf_base_dir, self.netperf_file) self.netperf_path = os.path.join(self.netperf_base_dir, self.netperf_file) logging.debug("Create remote session") self.session = remote.remote_login(self.client, self.address, self.port, self.username, self.password, self.prompt, self.linesep, timeout=360, status_test_command=self.status_test_command)
def setup_remote_ssh_key(hostname1, user1, password1, hostname2=None, user2=None, password2=None, port=22): ''' Setup up remote to remote login in another server by using public key If hostname2 is not supplied, setup to local. :param hostname1: the server wants to login other host :param hostname2: the server to be logged in :type hostname: str :param user: user to login :type user: str :param password: password :type password: str :param port: port number :type port: int ''' logging.debug('Performing SSH key setup on %s:%d as %s.' % (hostname1, port, user1)) try: session1 = remote.remote_login(client='ssh', host=hostname1, port=port, username=user1, password=password1, prompt=r'[$#%]') public_key = get_remote_public_key(session1) if hostname2 is None: # Simply create a session to local session2 = aexpect.ShellSession("sh", linesep='\n', prompt='#') else: session2 = remote.remote_login(client='ssh', host=hostname2, port=port, username=user2, password=password2, prompt=r'[$#%]') session2.cmd_output('mkdir -p ~/.ssh') session2.cmd_output('chmod 700 ~/.ssh') session2.cmd_output("echo '%s' >> ~/.ssh/authorized_keys; " % public_key) session2.cmd_output('chmod 600 ~/.ssh/authorized_keys') logging.debug('SSH key setup on %s complete.', session2) except Exception as err: logging.debug('SSH key setup has failed: %s', err) try: session1.close() session2.close() except: pass
def __init__(self, address, netperf_path, md5sum="", local_path="", client="ssh", port="22", username="******", password="******", check_command=None): """ Class NetperfPackage just represent the netperf package Init NetperfPackage class. :param address: Remote host or guest address :param netperf_path: Remote netperf path :param me5sum: Local netperf package me5sum :param local_path: Local netperf (path or link) path :param client: The client to use ('ssh', 'telnet' or 'nc') :param port: Port to connect to :param username: Username (if required) :param password: Password (if required) """ super(NetperfPackage, self).__init__(address, client, username, password, port, netperf_path) self.local_netperf = local_path self.pack_suffix = "" if client == "nc": self.prompt = r"^\w:\\.*>\s*$" self.linesep = "\r\n" else: self.prompt = "^\[.*\][\#\$]\s*$" self.linesep = "\n" if self.remote_path.endswith("tar.bz2"): self.pack_suffix = ".tar.bz2" self.decomp_cmd = "tar jxvf" elif self.remote_path.endswith("tar.gz"): self.pack_suffix = ".tar.gz" self.decomp_cmd = "tar zxvf" self.netperf_dir = self.remote_path.rstrip(self.pack_suffix) self.netperf_base_dir = os.path.dirname(self.remote_path) self.netperf_exec = os.path.basename(self.remote_path) logging.debug("Create remote session") self.session = remote.remote_login(self.client, self.address, self.port, self.username, self.password, self.prompt, self.linesep, timeout=360) self.build_tool = True if check_command: netperf_status = self.session.cmd_status("which %s" % check_command) if netperf_status == 0: self.build_tool = False if self.build_tool: if utils.is_url(local_path): logging.debug("Download URL file to local path") tmp_dir = data_dir.get_download_dir() self.local_netperf = utils.unmap_url_cache(tmp_dir, local_path, md5sum) self.push_file(self.local_netperf)
def __init__(self, address, source, client="ssh", file_transfer_client="scp", port="22", username="******", password="******", make_flags="", build_dir="/tmp", build_dir_prefix=None, linesep="\n", prompt="^(root@[^:]*[^\#\$]*[\#\$]\s*|\[.*\][\#\$]\s*)$"): """ :param address: Remote host or guest address :param source: Directory containing the source on the machine where this script is running :param client: The client to use ('ssh', 'telnet' or 'nc') :param file_transfer_client: The file transfer client to use ('scp' or 'rss') :param port: Port to connect to :param username: Username (if required) :param password: Password (if required) :param make_flags: Flags to pass to the make process :param build_dir: Where to copy and build the files on target :param build_dir_prefix: What to name the build directory on target (default: the name of the source directory) """ def full_build_path(build_dir, directory_prefix, make_flags): """ Generates the full path for the build using the make flags and supplied build location. :return: The full path as a string """ extra_flags_hash = hashlib.sha1() extra_flags_hash.update(make_flags) directory_name = "%s-%s" % (directory_prefix, (extra_flags_hash.hexdigest())[:8]) return os.path.join(build_dir, directory_name) self.address = address self.source = os.path.normpath(source) self.client = client self.file_transfer_client = file_transfer_client self.port = port self.username = username self.password = password self.make_flags = make_flags self.build_dir = build_dir self.linesep = linesep self.prompt = prompt if build_dir_prefix is None: build_dir_prefix = os.path.basename(source) self.full_build_path = full_build_path(build_dir, build_dir_prefix, make_flags) self.session = remote.remote_login(self.client, self.address, self.port, self.username, self.password, self.prompt, self.linesep, timeout=360)
def __init__(self, address, netperf_path, md5sum="", netperf_source="", client="ssh", port="22", username="******", password="******", compile_option="--enable-demo=yes", install=True): """ Init NetperfServer class. :param address: Remote host or guest address :param netperf_path: Remote netperf path :param me5sum: Local netperf package me5sum :param netperf_source: netperf source file (path or link) which will transfer to remote :param client: The client to use ('ssh', 'telnet' or 'nc') :param port: Port to connect to :param username: Username (if required) :param password: Password (if required) :param compile_option: Compile option for netperf :param install: Whether need install netperf or not. """ self.client = client if client == "nc": self.prompt = r"^\w:\\.*>\s*$" self.linesep = "\r\n" self.status_test_command = "echo %errorlevel%" else: self.prompt = "^\[.*\][\#\$]\s*$" self.linesep = "\n" self.status_test_command = "echo $?" self.package = NetperfPackage(address, netperf_path, md5sum, netperf_source, client, port, username, password) self.netserver_path, self.netperf_path = self.package.install( install, compile_option) logging.debug("Create remote session") self.session = remote.remote_login( client, address, port, username, password, self.prompt, self.linesep, timeout=360, status_test_command=self.status_test_command)
def __init__(self, address, netperf_path, md5sum="", local_path="", client="ssh", port="22", username="******", password="******"): """ Class NetperfPackage just represent the netperf package Init NetperfPackage class. :param address: Remote host or guest address :param netperf_path: Remote netperf path :param me5sum: Local netperf package me5sum :param local_path: Local netperf (path or link) path :param client: The client to use ('ssh', 'telnet' or 'nc') :param port: Port to connect to :param username: Username (if required) :param password: Password (if required) """ super(NetperfPackage, self).__init__(address, client, username, password, port, netperf_path) self.local_netperf = local_path self.pack_suffix = "" if client == "nc": self.prompt = r"^\w:\\.*>\s*$" self.linesep = "\r\n" else: self.prompt = "^\[.*\][\#\$]\s*$" self.linesep = "\n" if self.remote_path.endswith("tar.bz2"): self.pack_suffix = ".tar.bz2" self.decomp_cmd = "tar jxvf" elif self.remote_path.endswith("tar.gz"): self.pack_suffix = ".tar.gz" self.decomp_cmd = "tar zxvf" self.netperf_dir = self.remote_path.rstrip(self.pack_suffix) self.netperf_base_dir = os.path.dirname(self.remote_path) self.netperf_exec = os.path.basename(self.remote_path) if utils.is_url(local_path): logging.debug("Download URL file to local path") tmp_dir = data_dir.get_download_dir() self.local_netperf = utils.unmap_url_cache(tmp_dir, local_path, md5sum) self.push_file(self.local_netperf) logging.debug("Create remote session") self.session = remote.remote_login(self.client, self.address, self.port, self.username, self.password, self.prompt, self.linesep, timeout=360)
def _start_tcpdump(self): cmd_template = "%s -npvvvi any 'port 68 or port 546'" if self._params.get("remote_preprocess") == "yes": client = self._params.get('remote_shell_client', 'ssh') port = self._params.get('remote_shell_port', '22') prompt = self._params.get('remote_shell_prompt', '#') address = self._params.get('remote_node_address') username = self._params.get('remote_node_user') password = self._params.get('remote_node_password') rsession = None try: rsession = remote.remote_login(client, address, port, username, password, prompt) tcpdump_bin = rsession.cmd_output("which tcpdump") rsession.close() except process.CmdError: rsession.close() raise exceptions.TestError("Can't find tcpdump binary!") cmd = cmd_template % tcpdump_bin.strip() logging.debug("Run '%s' on host '%s'", cmd, address) login_cmd = ("ssh -o UserKnownHostsFile=/dev/null " "-o StrictHostKeyChecking=no " "-o PreferredAuthentications=password -p %s %s@%s" % (port, username, address)) self._tcpdump = aexpect.ShellSession( login_cmd, output_func=_update_address_cache, output_params=(self,)) remote.handle_prompts(self._tcpdump, username, password, prompt) self._tcpdump.sendline(cmd) else: cmd = cmd_template % utils_path.find_command("tcpdump") self._tcpdump = aexpect.Tail(command=cmd, output_func=_tcpdump_handler, output_params=(self, "tcpdump.log")) if not utils_misc.wait_for(lambda: self._tcpdump.is_alive(), 1.0, 0.1, 0.1): logging.warn("Could not start tcpdump") logging.warn("Status: %s", self._tcpdump.get_status()) msg = utils_misc.format_str_for_message(self._tcpdump.get_output()) logging.warn("Output: %s", msg)
def _start_tcpdump(self): cmd_template = "%s -npvvvi any 'port 68 or port 546'" if self._params.get("remote_preprocess") == "yes": client = self._params.get('remote_shell_client', 'ssh') port = self._params.get('remote_shell_port', '22') prompt = self._params.get('remote_shell_prompt', '#') address = self._params.get('remote_node_address') username = self._params.get('remote_node_user') password = self._params.get('remote_node_password') rsession = None try: rsession = remote.remote_login(client, address, port, username, password, prompt) tcpdump_bin = rsession.cmd_output("which tcpdump") rsession.close() except process.CmdError: rsession.close() raise exceptions.TestError("Can't find tcpdump binary!") cmd = cmd_template % tcpdump_bin.strip() logging.debug("Run '%s' on host '%s'", cmd, address) login_cmd = ("ssh -o UserKnownHostsFile=/dev/null " "-o StrictHostKeyChecking=no " "-o PreferredAuthentications=password -p %s %s@%s" % (port, username, address)) self._tcpdump = aexpect.ShellSession( login_cmd, output_func=_update_address_cache, output_params=(self,)) remote.handle_prompts(self._tcpdump, username, password, prompt) self._tcpdump.sendline(cmd) else: cmd = cmd_template % utils_path.find_command("tcpdump") self._tcpdump = aexpect.Tail(command=cmd, output_func=_tcpdump_handler, output_params=(self, "tcpdump.log")) if utils_misc.wait_for(lambda: not self._tcpdump.is_alive(), 0.1, 0.1, 1.0): logging.warn("Could not start tcpdump") logging.warn("Status: %s", self._tcpdump.get_status()) msg = utils_misc.format_str_for_message(self._tcpdump.get_output()) logging.warn("Output: %s", msg)
def login(self, nic_index=0, timeout=LOGIN_TIMEOUT, username=None, password=None): """ Log into the guest via SSH/Telnet/Netcat. If timeout expires while waiting for output from the guest (e.g. a password prompt or a shell prompt) -- fail. :param nic_index: The index of the NIC to connect to. :param timeout: Time (seconds) before giving up logging into the guest. :return: A ShellSession object. """ error.context("logging into '%s'" % self.name) if not username: username = self.params.get("username", "") if not password: password = self.params.get("password", "") prompt = self.params.get("shell_prompt", "[\#\$]") linesep = eval("'%s'" % self.params.get("shell_linesep", r"\n")) client = self.params.get("shell_client") ip_version = self.params.get("ip_version", "ipv4").lower() neigh_attach_if = "" address = self.wait_for_get_address(nic_index, timeout=360, ip_version=ip_version) if address and address.lower().startswith("fe80"): neigh_attach_if = utils_net.get_neigh_attch_interface(address) port = self.get_port(int(self.params.get("shell_port"))) log_filename = ("session-%s-%s.log" % (self.name, utils_misc.generate_random_string(4))) session = remote.remote_login(client, address, port, username, password, prompt, linesep, log_filename, timeout, interface=neigh_attach_if) session.set_status_test_command(self.params.get("status_test_command", "")) self.remote_sessions.append(session) return session
def __init__(self, params, address, source, shell_client=None, shell_port=None, file_transfer_client=None, file_transfer_port=None, username=None, password=None, make_flags="", build_dir=None, build_dir_prefix=None, shell_linesep=None, shell_prompt=None): """ :param params: Dictionary with test parameters, used to get the default values of all named parameters. :param address: Remote host or guest address :param source: Directory containing the source on the machine where this script is running :param shell_client: The client to use ('ssh', 'telnet' or 'nc') :param shell_port: Port to connect to for the shell client :param file_transfer_client: The file transfer client to use ('scp' or 'rss') :param file_transfer_port: Port to connect to for the file transfer client :param username: Username (if required) :param password: Password (if required) :param make_flags: Flags to pass to the make process, default: "" :param build_dir: Where to copy and build the files on target. If None, use params['tmp_dir'] :param build_dir_prefix: What to name the build directory on target If None, use the name of the source directory. :param shell_linesep: Line separator in the shell :param shell_prompt: Regexp that matches the prompt in the shell. """ def full_build_path(build_dir, directory_prefix, make_flags): """ Generates the full path for the build using the make flags and supplied build location. :return: The full path as a string """ extra_flags_hash = hashlib.sha1() extra_flags_hash.update(make_flags) directory_name = "%s-%s" % (directory_prefix, (extra_flags_hash.hexdigest())[:8]) return os.path.join(build_dir, directory_name) def def_helper(arg, param, default): if arg is None: return params.get(param, default) else: return arg self.address = address self.source = os.path.normpath(source) self.client = def_helper(shell_client, "shell_client", "ssh") self.port = def_helper(shell_port, "shell_port", "22") self.file_transfer_client = def_helper(file_transfer_client, "file_transfer_client", "scp") self.file_transfer_port = def_helper(file_transfer_port, "file_transfer_port", "22") self.username = def_helper(username, "username", "root") self.password = def_helper(password, "password", "redhat") self.make_flags = make_flags self.build_dir = def_helper(build_dir, "tmp_dir", "/tmp") if build_dir_prefix is None: build_dir_prefix = os.path.basename(source) self.full_build_path = full_build_path(self.build_dir, build_dir_prefix, make_flags) self.linesep = def_helper(shell_linesep, "shell_linesep", "\n") self.prompt = def_helper(shell_prompt, "shell_prompt", "^\[.*\][\#\$]\s*)$") self.session = remote.remote_login(self.client, self.address, self.port, self.username, self.password, self.prompt, self.linesep, timeout=360)
def __init__(self, address, netperf_path, md5sum="", netperf_source="", client="ssh", port="22", username="******", password="******"): """ Class NetperfPackage just represent the netperf package Init NetperfPackage class. :param address: Remote host or guest address :param netperf_path: Installed netperf path :param me5sum: Local netperf package me5sum :param netperf_source: source netperf (path or link) path :param client: The client to use ('ssh', 'telnet' or 'nc') :param port: Port to connect to :param username: Username (if required) :param password: Password (if required) """ super(NetperfPackage, self).__init__(address, client, username, password, port, netperf_path) self.netperf_source = netperf_source self.pack_suffix = "" self.netperf_dir = None self.build_tool = False self.md5sum = md5sum self.netperf_base_dir = self.remote_path self.netperf_file = os.path.basename(self.netperf_source) if client == "nc": self.prompt = r"^\w:\\.*>\s*$" self.linesep = "\r\n" else: self.prompt = "^\[.*\][\#\$]\s*$" self.linesep = "\n" if self.netperf_source.endswith("tar.bz2"): self.pack_suffix = ".tar.bz2" self.decomp_cmd = "tar jxvf" elif self.netperf_source.endswith("tar.gz"): self.pack_suffix = ".tar.gz" self.decomp_cmd = "tar zxvf" self.netperf_dir = os.path.join( self.remote_path, self.netperf_file.rstrip(self.pack_suffix)) if self.pack_suffix: self.netserver_path = os.path.join(self.netperf_dir, "src/netserver") self.netperf_path = os.path.join(self.netperf_dir, "src/netperf") else: self.netserver_path = os.path.join(self.netperf_base_dir, self.netperf_file) self.netperf_path = os.path.join(self.netperf_base_dir, self.netperf_file) logging.debug("Create remote session") self.session = remote.remote_login(self.client, self.address, self.port, self.username, self.password, self.prompt, self.linesep, timeout=360)