### RPyC Server Command-Line Example Source: https://github.com/intel/mfd-connect/blob/main/README.md An example command-line interface for starting the mfd_connect RPyC server. It shows how to specify the port, log file path, and SSL certificate/key file paths. SSL is optional. ```bash python -m mfd_connect.rpyc_server -p/--port -l/--log --ssl-keyfile --ssl-certfile ``` -------------------------------- ### RPyC Server Setup Example Source: https://github.com/intel/mfd-connect/blob/main/README.md Example of how to run an RPyC server compatible with PythonConnection. This is for demonstration purposes and might require adjustments based on your environment. ```APIDOC ## RPyC Server Setup Example ### Description This section provides an example command to start an RPyC server using `mfd_connect.rpyc_server`. The server can be configured with a specific port, log file, and SSL certificates. ### Method Command Line Execution ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash python -m mfd_connect.rpyc_server -p/--port -l/--log --ssl-keyfile --ssl-certfile ``` **Notes:** - The port and log file parameters are optional. If not provided, default values from the module will be used for the port, and logs will be written to console output. - SSL key and certificate files are optional. If not provided, the server will run without SSL. ### Response #### Success Response (Server Running) - The server will start listening on the specified port. #### Response Example N/A ``` -------------------------------- ### Start and monitor a remote process using LocalConnection Source: https://github.com/intel/mfd-connect/blob/main/README.md This Python snippet demonstrates how to initiate a process on a local machine using the `LocalConnection` class and then stream its standard output. Ensure the `mfd-connect` library is installed. The function takes a command string and an optional `shell` argument. ```python from mfd_connect import LocalConnection conn = LocalConnection() proc = conn.start_process(command="dir C:\\", shell=True) for line in proc.get_stdout_iter(): print(line.strip()) ``` -------------------------------- ### Python Deployment Setup Tool Source: https://github.com/intel/mfd-connect/blob/main/README.md Details the 'SetupPythonForResponder' class, which prepares a Python environment with an RPyC server on a remote machine. It connects via SSH or WinRM, checks for an existing server, downloads and unpacks Python from a specified Artifactory URL, and starts the RPyC server. Artifactory credentials are optional. ```python from typing import Optional class SetupPythonForResponder: def __init__(self, ip: str, username: str, password: str, artifactory_url: str, artifactory_username: Optional[str] = None, artifactory_password: Optional[str] = None): self.ip = ip self.username = username self.password = password self.artifactory_url = artifactory_url self.artifactory_username = artifactory_username self.artifactory_password = artifactory_password # ... (logic to connect, check server, download, unpack, and start RPyC server) ... def setup(self): # ... (implementation of the setup process) ... pass ``` -------------------------------- ### PythonConnection Start Process on Windows Source: https://github.com/intel/mfd-connect/blob/main/README.md Starts a process using the start tool in the background on Windows systems. This method returns a `WindowsRPyCProcessByStart` object and allows specifying a NUMA node preference. ```python python_connection.start_process_by_start_tool(command="your_command", numa_node=0) ``` -------------------------------- ### Start Process with CPU Affinity Source: https://github.com/intel/mfd-connect/blob/main/README.md Starts a process on a local connection and binds it to specific CPU cores. Supports various formats for specifying CPU affinity, including single cores, lists, and ranges. ```python from mfd_connect import LocalConnection conn = LocalConnection() # Example with a list of CPU cores proc = conn.start_process(command="iperf -s -B 127.0.0.1", cpu_affinity=[1, 3, 7]) # Example with a range of CPU cores # proc = conn.start_process(command="iperf -s -B 127.0.0.1", cpu_affinity="3-6") # Example with a combination of numbers and ranges # proc = conn.start_process(command="iperf -s -B 127.0.0.1", cpu_affinity="1, 3-6") ``` -------------------------------- ### InteractiveSSHProcess Management Source: https://github.com/intel/mfd-connect/blob/main/README.md Manage and interact with processes started via InteractiveSSHConnection. ```APIDOC ## InteractiveSSHProcess Management ### Description Represents a process started on a remote machine, providing methods to monitor and control its execution. ### Methods #### `running` - **Method**: `running` - **Description**: Returns `True` if the process is currently running, `False` otherwise. Based on the prompt in the channel. - **Return Type**: boolean #### `stop` - **Method**: `stop` - **Description**: Stops the process gracefully using CTRL+C. - **Parameters**: - **wait** (integer) - Required - The time in seconds to wait for the process to stop. #### `kill` - **Method**: `kill` - **Description**: Forcefully kills the process using a specified signal. - **Parameters**: - **wait** (integer) - Required - The time in seconds to wait for the process to stop. - **with_signal** (string) - Required - The signal to use for killing the process (e.g., 'SIGKILL'). #### `wait` - **Method**: `wait` - **Description**: Waits for the process to finish execution. - **Parameters**: - **timeout** (integer) - Optional - The time in seconds to wait for the process to finish. #### `stdout_text` - **Method**: `stdout_text` - **Description**: Returns the standard output of the process as a string. - **Return Type**: string #### `return_code` - **Method**: `return_code` - **Description**: Returns the exit code of the process. Uses `echo $? / %errorlevel%`. - **Return Type**: integer #### `get_stdout_iter` - **Method**: `get_stdout_iter` - **Description**: Returns an iterator over the standard output of the process. ``` -------------------------------- ### PythonConnection Start Process Source: https://github.com/intel/mfd-connect/blob/main/README.md Launches a process in the background on the remote machine, making it accessible later. This is a fundamental method for asynchronous task execution. ```python python_connection.start_process("your_command") ``` -------------------------------- ### Output Redirection for Processes Source: https://github.com/intel/mfd-connect/blob/main/README.md Details on how to redirect the output of processes started via PythonConnection or SSHConnection to a file. ```APIDOC ## Output Redirection for Processes ### Description This section explains how to redirect the standard output and error streams of processes started using methods like `start_process` in PythonConnection or SSHConnection. ### Method Parameter Configuration for `start_process` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **log_file** (bool) - If set to True, the output of the process will be redirected to a file. The file will be generated in the `~/execution_logs` directory and named based on the command's SHA value. - **output_file** (str | Path) - An optional string or `pathlib.Path` object specifying the exact path to the file where the output should be redirected. **Note:** `log_file` and `output_file` are mutually exclusive. Use one or the other for redirection. ### Request Example ```python # Using log_file process = connection.start_process("your_command", log_file=True) # Using output_file process = connection.start_process("your_command", output_file="/path/to/custom/log.txt") ``` ### Response #### Success Response (Process Object) - **log_path** (Path) - A `pathlib.Path` object pointing to the log file used for redirection. You can read the output using `process.log_path.read_text()`. - **log_file_stream** (file stream) - An opened file stream for the `log_path`. Remember to close it after use: `process.log_file_stream.close()`. #### Response Example ```python # After starting a process with redirection log_content = process.log_path.read_text() print(log_content) process.log_file_stream.close() ``` ``` -------------------------------- ### Start Process on Remote Host Source: https://github.com/intel/mfd-connect/blob/main/README.md Starts a process on the remote machine, returning an InteractiveSSHProcess object for interaction. Only one process can run concurrently. Output and error streams can be redirected. ```python command = "ping -c 5 google.com" process = connection.start_process(command) # Interact with the process using process object methods ``` -------------------------------- ### Control InteractiveSSHProcess Source: https://github.com/intel/mfd-connect/blob/main/README.md Provides methods to manage a process started on a remote machine. Includes checking if running, stopping gracefully, forceful killing, waiting for completion, and retrieving output. ```python # Assuming 'process' is an InteractiveSSHProcess object if process.running(): print("Process is running.") # Stop the process gracefully # process.stop(wait=5) # Kill the process forcefully # process.kill(wait=5, with_signal='SIGKILL') # Wait for the process to finish # process.wait(timeout=10) # Get stdout as text stdout_output = process.stdout_text() # Get return code return_code = process.return_code() # Get stdout as an iterator stdout_iterator = process.get_stdout_iter() ``` -------------------------------- ### Connection - Get OS Information Source: https://github.com/intel/mfd-connect/blob/main/README.md Retrieves various details about the client operating system. ```APIDOC ## GET /system-info ### Description Retrieves information about the client's operating system, including type, name, and bitness, as well as CPU architecture. ### Method GET ### Endpoint `/system-info` ### Parameters #### Query Parameters - **cached** (bool) - Optional - Whether to use cached system data (default: True). ### Response #### Success Response (200) - **os_type** (string) - The type of the operating system (e.g., 'Linux', 'Windows'). - **os_name** (string) - The name of the operating system. - **os_bitness** (integer) - The bitness of the operating system (e.g., 64). - **cpu_architecture** (string) - The CPU architecture of the system. #### Response Example ```json { "os_type": "Linux", "os_name": "Ubuntu", "os_bitness": 64, "cpu_architecture": "x86_64" } ``` ``` -------------------------------- ### AsyncConnection Start Process Source: https://github.com/intel/mfd-connect/blob/main/README.md Starts a process in the background on the remote machine, allowing for future access to the `RemoteProcess` object. This is useful for long-running tasks. ```python async_connection.start_process("your_command") ``` -------------------------------- ### Usage Example: Reading File Content via SSHConnection Source: https://github.com/intel/mfd-connect/blob/main/mfd_connect/pathlib/PATHLIB.md Demonstrates how to establish an SSH connection, create a path object for a remote file, read its text content, and print it. This requires the SSHConnection to be properly configured with credentials and IP address. ```python conn = SSHConnection(username="", password='', ip="") f = conn.path(r'~/logs.txt') content = f.read_text() print(content) ``` -------------------------------- ### AsyncConnection Start Multiple Processes Source: https://github.com/intel/mfd-connect/blob/main/README.md Initiates multiple processes in the background. This method is recommended when a command line triggers more than one process. Currently implemented for ssh, tunneled_ssh, and local connections. ```python async_connection.start_processes("command1 && command2") ``` -------------------------------- ### Get System Information Source: https://github.com/intel/mfd-connect/blob/main/README.md Gathers comprehensive details about the remote host, useful for logging system information. The `SystemInfo` dataclass is defined in `mfd-typing.os_values.py`. ```python from mfd_connect.connection import SSHConnection connection = SSHConnection(ip="x.x.x.x") system_info = connection.get_system_info() print(f"System Hostname: {system_info.hostname}") print(f"System OS Name: {system_info.os_name}") print(f"System OS Version: {system_info.os_version}") ``` -------------------------------- ### TelnetConnection: Get Output After User Action Source: https://github.com/intel/mfd-connect/blob/main/README.md Retrieves the output generated after a specific user action, such as pressing a key. This is useful for capturing dynamic responses in interactive sessions. ```python from mfd_connect.connections.telnet import TelnetConnection # Assuming telnet_conn is an initialized TelnetConnection object # output = telnet_conn.get_output_after_user_action() ``` -------------------------------- ### Get Remote OS Information Source: https://github.com/intel/mfd-connect/blob/main/README.md Retrieves the operating system type and name from the remote machine. ```python os_type = connection.get_os_type() os_name = connection.get_os_name() print(f"OS Type: {os_type}, OS Name: {os_name}") ``` -------------------------------- ### Execute PowerShell Commands via RPyCConnection and LocalConnection Source: https://github.com/intel/mfd-connect/blob/main/README.md This code example illustrates how to execute PowerShell commands on a remote system using the `execute_powershell` method, which is supported by both `RPyCConnection` and `LocalConnection`. This functionality allows for Windows-specific command execution. ```python # Example usage (RPyCConnection or LocalConnection assumed): # conn.execute_powershell("Get-Process") ``` -------------------------------- ### AsyncConnection Get OS Information Source: https://github.com/intel/mfd-connect/blob/main/README.md Retrieves operating system details such as type, name, and bitness from the remote machine. These methods rely on specific check commands. OS type, name, and bitness definitions can be found in the mfd-typing module's os_values.py. ```python async_connection.get_os_type() ``` ```python async_connection.get_os_name() ``` ```python async_connection.get_os_bitness() ``` -------------------------------- ### PythonConnection Get Requirements Version Source: https://github.com/intel/mfd-connect/blob/main/README.md Reads the Portable Python SHA from the `requirements_version` file, returning it if the code was executed using Portable Python. Returns None otherwise. ```python python_connection.get_requirements_version() ``` -------------------------------- ### PythonConnection Get CPU Architecture Source: https://github.com/intel/mfd-connect/blob/main/README.md Fetches the CPU architecture of the client OS by executing a check command. CPU architecture details can be found in the mfd-typing module's cpu_values.py. ```python python_connection.get_cpu_architecture() ``` -------------------------------- ### PythonConnection Get OS Information Source: https://github.com/intel/mfd-connect/blob/main/README.md Retrieves operating system type, name, and bitness from the remote machine. These methods execute specific check commands. Definitions for OS types, names, and bitness are located in the mfd-typing module's os_values.py. ```python python_connection.get_os_type() ``` ```python python_connection.get_os_name() ``` ```python python_connection.get_os_bitness() ``` -------------------------------- ### Copy File/Directory with MFD Connect Source: https://github.com/intel/mfd-connect/blob/main/README.md The `copy` function facilitates file and directory transfers between different connection types. It supports various source and target path specifications, including wildcards for specific file extensions. Ensure MFD-FTP>=1.0.0 is installed on both source and destination for large file transfers. Remote RPyC copies may create temporary connections with extended timeouts. ```python copy(src_conn: "Connection", dst_conn: "Connection", source: Union[str, Path], target: Union[str, Path], timeout: int = 600) -> None """ Copy file/directory to the target. :param src_conn: Source connection object :param dst_conn: Destination connection object :param source: Path to file or directory to be copied :param target: Path to where file or directory should be copied. :param timeout: Timeout to wait for copying (used in rpyc remote only) """ ``` ```python copy(src_conn=SSHCConnection("", username="***", password="***"), dst_conn=RPyCConnection(""), source="/tmp/iperf/iperf.exe", target="/tmp/tools/iperf.exe") ``` ```python copy(src_conn=SSHCConnection("", username="***", password="***"), dst_conn=LocalConnection, source="/tmp/iperf/*", target="/tmp/tools") ``` ```python copy(src_conn=SSHCConnection("", username="***", password="***"), dst_conn=LocalConnection, source="/tmp/iperf", target="/tmp/tools") ``` ```python copy(src_conn=RPyCConnection(""), dst_conn=RPyCConnection(""), source="/tmp/iperf/*.pkg", target="/tmp/tools/") copy(src_conn=SSHConnection("", username="***", password="***"), dst_conn=SSHConnection("", username="***", password="***"), source="/tmp/iperf/*.pkg", target="/tmp/tools/") copy(src_conn=RPyCConnection(""), dst_conn=SSHConnection("", username="***", password="***"), source="/tmp/iperf/*.pkg", target="/tmp/tools/") ``` -------------------------------- ### AsyncConnection Get CPU Architecture Source: https://github.com/intel/mfd-connect/blob/main/README.md Retrieves the CPU architecture of the remote client OS. This method executes a check command. CPU architecture definitions are available in the mfd-typing module's cpu_values.py. ```python async_connection.get_cpu_architecture() ``` -------------------------------- ### Paramiko Channel Execution Behavior Source: https://github.com/intel/mfd-connect/blob/main/README.md Explains that both 'start_process' and 'execute_command' create a new Paramiko channel for each command, which is the recommended approach. When a channel is closed, any processes started within it are terminated. To maintain process longevity, streams need to be redirected or the 'SSHProcess' object must be retained, as it holds references to stdout/err/in streams. ```python class SSHProcess: # ... (internal implementation details) ... pass def execute_command(command, timeout=None): # Internally creates an SSHProcess object to handle commands and timeouts. # If timeout is specified, an SSHProcess is used to manage command execution time. pass def start_process(command): # Creates a new Paramiko channel for the command. # Processes are killed when the channel is closed. pass ``` -------------------------------- ### RPyCConnection Deployment Parameters Source: https://github.com/intel/mfd-connect/blob/main/README.md Outlines the constructor arguments for 'RPyCConnection' related to deployment. 'enable_deploy' triggers the deployment process if a connection cannot be established. 'share_url' points to the Artifactory package. The tool attempts to connect on the default port and retries on a deployment port if necessary, initiating deployment if all attempts fail. ```python from typing import Optional class RPyCConnection: def __init__(self, port: int, enable_deploy: bool = False, deploy_username: Optional[str] = None, deploy_password: Optional[str] = None, share_url: Optional[str] = None, share_username: Optional[str] = None, share_password: Optional[str] = None): self.port = port self.enable_deploy = enable_deploy self.deploy_username = deploy_username self.deploy_password = deploy_password self.share_url = share_url self.share_username = share_username self.share_password = share_password # ... (logic to attempt connection, retry on deploy port, and initiate deployment if needed) ... def connect(self): # ... (connection logic including deployment fallback) ... pass ``` -------------------------------- ### PxsshConnection API Source: https://github.com/intel/mfd-connect/blob/main/README.md Documentation for the PxsshConnection class, leveraging pexpect's pxssh for SSH connections. ```APIDOC ## PxsshConnection ### Description PxsshConnection is a Python module that leverages the pxssh class from the pexpect library to establish and manage SSH (Secure Shell) connections. This module provides a high-level interface for interacting with remote servers over SSH. The PxsshConnection module is designed to accept a `prompts` parameter as input. This parameter represents the expected prompt that will appear after the execution of a command. The module then matches this expected prompt with the actual prompt that is returned. This functionality allows for precise control and handling of command execution, ensuring that the operation has completed as expected before proceeding. ### Constructor Parameters * `prompts` (str) - Default: "# $" - Represents the expected prompt(s) after command execution. ### References * https://pexpect.readthedocs.io/en/stable/api/pxssh.html * https://pexpect.sourceforge.net/pxssh.html ``` -------------------------------- ### Python mfd_connect Constructor Parameters Source: https://github.com/intel/mfd-connect/blob/main/README.md Defines the parameters for the constructor of the MFD Connect client, used for establishing connections to remote hosts. It includes options for IP address, port, timeouts, SSL configuration, and deployment credentials. ```python def __init__( self, ip: Union["IPAddress", str], *, port: int = None, path_extension: str = None, connection_timeout: int = 360, default_timeout: int | None = None, retry_timeout: Optional[int] = None, retry_time: int = 5, enable_bg_serving_thread: bool = True, model: Optional["BaseModel"] = None, enable_deploy: bool = False, deploy_username: str = None, deploy_password: str = None, share_url: str = None, share_username: str = None, share_password: str = None, ssl_keyfile: str | None = None, ssl_certfile: str | None = None, **kwargs, ) -> None: # noqa: D200 ``` -------------------------------- ### SerialConnection API Source: https://github.com/intel/mfd-connect/blob/main/README.md Documentation for the SerialConnection class, used for establishing connections to serial devices. ```APIDOC ## SerialConnection ### Description Allows to create a connection to serial device. Unlike other connections, this class requires an established connection to host where serial device is present. This is caused by the fact that SerialConnection first connects to the host, redirects the serial device through netcat and only then creates a TelnetConnection to redirected port on the host. ### Parameters * `is_veloce` (bool) - Optional - If true, increases timeout for executing commands due to high response time of Veloce setups. * `baudrate` (int) - Optional - Used to initialize connection to serial device using appropriate baudrate if it has not been used on the setup previously. * `serial_logs_path` (str) - Optional - Path to save serial movement logs. ### Methods * `methods from Connection` * `get_screen_field_value(field_regex: str, group_name: Optional[str]) -> Optional[str]` * `fire_and_forget` - execute command without getting output, parsing return code or waiting for prompt to reappear * `execute_command` - it runs command and waits for command to finish * `get_os_type` - it runs check command and return type of client OS * `get_os_name` - it runs check command and return name of client OS * `wait_for_string` - it waits for given string or list of strings till timeout. * `go_to_option_on_screen` - it moves on screen till found given option * `send_key` - it sends given Serial Key Code from `SerialKeyCode`. * `get_output_after_user_action` - it returns output after user action, eg. pressing key * `disconnect()` - stops netcat server on host and disconnects from it, also calls `stop_logging()`. ### Supported Shells * POSIX * UEFI Shell ``` -------------------------------- ### WinRmConnection API Source: https://github.com/intel/mfd-connect/blob/main/README.md Documentation for the WinRmConnection class, which uses pywinrm for Windows Remote Management. ```APIDOC ## WinRmConnection ### Description Connection uses `pywinrm` library to communicate with server via Windows Remote Management protocol. ### Parameters * `ip` (str) - Required - IP address of the server. * `username` (str) - Required - Username for authentication. * `password` (str) - Required - Password for authentication. ### Unsupported Methods/APIs * In `execute_command` method, the following parameters are not functional: `input_data`, `cwd`, `timeout`, `env`, `discard_stdout`, `discard_stderr`, `shell`. * `restart_platform`, `shutdown_platform` and `wait_for_host` APIs are not implemented. * In process objects, the following APIs are not implemented: `stdin_stream`, `stdout_stream`, `stderr_stream`, `get_stdout_iter`, `get_stderr_iter`, `wait`. ``` -------------------------------- ### Initialize InteractiveSSHConnection Source: https://github.com/intel/mfd-connect/blob/main/README.md Initializes an InteractiveSSHConnection instance for SSH server communication. Requires server credentials and optional key path. Host key verification can be skipped. ```python from intel_mfd_connect.ssh import InteractiveSSHConnection connection = InteractiveSSHConnection( ip="your_server_ip", port=22, username="your_username", password="your_password", key_path=None, # Optional: path to SSH key skip_key_verification=False, # Set to True to skip host key verification model="your_model", default_timeout=30 ) ``` -------------------------------- ### Initialize SSH Connection with Paramiko Source: https://github.com/intel/mfd-connect/blob/main/README.md Initializes an SSH connection using the Paramiko library. Supports password or key-based authentication, optional host key verification skipping, and custom timeouts. Requires the 'paramiko' library. ```python SSHConnection(ip: str, port: int = 22, username: str, password: Optional[str], key_path: Optional[Union[List[Union[str, "Path"]], str, "Path"]] = None, skip_key_verification: bool = False, model: "BaseModel | None" = None, default_timeout: int | None = None,) """ Initialise SSHConnection. :param ip: IP address of SSH server :param port: port of SSH server :param username: Username for connection :param password: Password for connection, optional for using key, pass None for no password :param key_path: the filename, or list of filenames, of optional private key(s) and/or certs to try for authentication, supported types: RSAKey, DSSKey, ECDSAKey, Ed25519Key :param skip_key_verification: To skip checking of host's key, equivalent of StrictHostKeyChecking=no :param model: pydantic model of connection :param default_timeout: Set default_timeout property. """ ``` -------------------------------- ### Get Linux Kernel Version Source: https://github.com/intel/mfd-connect/blob/main/README.md Retrieves the kernel version of a remote Linux host using the 'uname -r' command. Requires an active 'Connection' object to the remote host. ```python from mfd_connect.connection import Connection def get_kernel_version_linux(connection: "Connection") -> str: """Gets Kernel version of remote Linux Host (uname -r).""" # Implementation omitted for brevity pass ``` -------------------------------- ### TelnetConnection API Source: https://github.com/intel/mfd-connect/blob/main/README.md Documentation for the TelnetConnection class, which supports various methods for command execution and interaction. ```APIDOC ## TelnetConnection ### Description Supports various methods for command execution and interaction over Telnet. ### Methods * `fire_and_forget` - execute command without getting output, parsing return code or waiting for prompt to reappear * `execute_command` - it runs command and waits for command to finish * `get_os_type` - it runs check command and return type of client OS * `get_os_name` - it runs check command and return name of client OS * `wait_for_string` - it waits for given string or list of strings till timeout. * `go_to_option_on_screen` - it moves on screen till found given option * `send_key` - it sends given Serial Key Code from `SerialKeyCode`. * `get_output_after_user_action` - it returns output after user action, eg. pressing key *Note: Invoking any other command from Connection on these classes may result in raising `NotImplementedError`.* ``` -------------------------------- ### Disconnect and Reboot Connection Source: https://github.com/intel/mfd-connect/blob/main/README.md Demonstrates how to disconnect from a machine and initiate a reboot sequence. This involves calling the disconnect method on the connection object and then rebooting the PDU. A wait_for_host method is also shown for ensuring the host is available after reboot. Requires appropriate user permissions for shutdown operations. ```python connection.disconnect() ``` ```python pdu.reboot() ``` ```python connection.wait_for_host(timeout=360) ``` -------------------------------- ### PxsshConnection: Establish SSH Connection with Prompt Matching Source: https://github.com/intel/mfd-connect/blob/main/README.md Leverages the `pxssh` class from the `pexpect` library to establish and manage SSH connections. It allows specifying expected prompts for precise command execution handling. The default prompt is '# $'. ```python from mfd_connect.connections.pxssh import PxsshConnection # Example initialization with default prompt # pxssh_conn = PxsshConnection(host='your_ssh_host', username='user', password='password') # Example initialization with custom prompt # pxssh_conn_custom = PxsshConnection(host='your_ssh_host', username='user', password='password', prompts='> ') ``` -------------------------------- ### TelnetConnection: Get Operating System Name Source: https://github.com/intel/mfd-connect/blob/main/README.md Executes a check command on the client to determine and return the name of the operating system. OS names are available in the `os_values.py` module within the `mfd-typing` package. ```python from mfd_connect.connections.telnet import TelnetConnection # Assuming telnet_conn is an initialized TelnetConnection object # os_name = telnet_conn.get_os_name() ``` -------------------------------- ### TelnetConnection: Get Operating System Type Source: https://github.com/intel/mfd-connect/blob/main/README.md Executes a check command on the client to determine and return the type of the operating system. Supported OS types are defined in the `os_values.py` module within the `mfd-typing` package. ```python from mfd_connect.connections.telnet import TelnetConnection # Assuming telnet_conn is an initialized TelnetConnection object # os_type = telnet_conn.get_os_type() ``` -------------------------------- ### InteractiveSSHConnection API Source: https://github.com/intel/mfd-connect/blob/main/README.md Documentation for the InteractiveSSHConnection class, which uses paramiko's invoke_shell for interactive SSH sessions. ```APIDOC ## InteractiveSSHConnection ### Description `InteractiveSSHConnection` is a connection type that leverages `paramiko` library to establish and manage SSH (Secure Shell) connections using `invoke_shell` API. Connection work in interactive mode, which means that it reads and writes to the single channel and waits for the prompt (in case of executing command). Prompt is used for checking if process is finished (in case of starting process). ``` -------------------------------- ### SolConnection Source: https://github.com/intel/mfd-connect/blob/main/README.md A connection class for Serial over LAN, supporting methods for interacting with serial devices and screens. ```APIDOC ## SolConnection ### Description It's a Connection for Serial over LAN. Supports methods from `Connection`, `wait_for_string`, `go_to_option_on_screen`, `get_output_after_user_action`, `send_key`, and `get_cwd`. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Supported Methods: - Methods from `Connection` - **wait_for_string** (str or list[str], timeout) - Waits for a given string or list of strings until timeout. - **go_to_option_on_screen** (str) - Moves on screen until the given option is found. - **get_output_after_user_action** (action) - Returns output after a user action (e.g., pressing a key). - **send_key** (SerialKeyCode) - Sends a given Serial Key Code from `SerialKeyCode`. - **get_cwd** () - Returns the current working directory. Raises `SolException` if unavailable. ``` -------------------------------- ### Generate MFD-Connect Docs (Shell) Source: https://github.com/intel/mfd-connect/blob/main/sphinx-doc/README.md This command initiates the documentation generation process for MFD-Connect using a Python script. Ensure you are in the correct directory and have the necessary Python environment activated. ```shell $ python generate_docs.py ``` -------------------------------- ### InteractiveSSHConnection Initialization and Disconnection Source: https://github.com/intel/mfd-connect/blob/main/README.md Initialize and disconnect from an SSH server using InteractiveSSHConnection. ```APIDOC ## InteractiveSSHConnection Initialization and Disconnection ### Description Initializes the InteractiveSSHConnection instance with server details and provides a method to close the connection. ### Methods #### `__init__` - **Method**: Constructor - **Parameters**: - **ip** (string) - Required - The IP address of the SSH server. - **port** (integer) - Required - The port of the SSH server. - **username** (string) - Required - The username for SSH authentication. - **password** (string) - Required - The password for SSH authentication. - **key_path** (string) - Optional - The path to the SSH private key file. - **skip_key_verification** (boolean) - Optional - If True, skips host key verification. - **model** (string) - Required - The model of the device. - **default_timeout** (integer) - Optional - The default timeout for operations in seconds. #### `disconnect` - **Method**: `disconnect` - **Description**: Closes the SSH connection gracefully. ``` -------------------------------- ### TelnetConnection: Navigate Screen Options Source: https://github.com/intel/mfd-connect/blob/main/README.md Moves through the screen interface until a specified option is found. This method facilitates automated navigation within text-based interfaces. ```python from mfd_connect.connections.telnet import TelnetConnection # Assuming telnet_conn is an initialized TelnetConnection object # success = telnet_conn.go_to_option_on_screen('option text') ``` -------------------------------- ### Connection - System Management Source: https://github.com/intel/mfd-connect/blob/main/README.md Provides methods for restarting and shutting down the remote platform. ```APIDOC ## POST /platform-management ### Description Manages the remote platform by allowing restarts or shutdowns. ### Method POST ### Endpoint `/platform-management` ### Parameters #### Request Body ```json { "action": "string" } ``` - **action** (string) - Required - The action to perform. Supported values: 'restart', 'shutdown'. ### Request Example ```json { "action": "restart" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the action has been initiated. #### Response Example ```json { "message": "Platform restart initiated." } ``` ``` -------------------------------- ### Execute Background Command with SSH Source: https://github.com/intel/mfd-connect/blob/main/README.md Demonstrates methods for executing commands in the background via SSH. Using 'start_process' or 'execute_command' with '&' requires stream redirection to keep the process alive in the OS. 'start_process' is recommended for explicit control. ```python # Option 1: Using start_process (Recommended) command = "sleep 10 &" process = connection.start_process(command, discard_stdout=True) # discard_stdout helps keep process alive # Option 2: Using execute_command with '&' and redirection # command = "sleep 10 > /dev/null 2>&1 &" # connection.execute_command(command) ``` -------------------------------- ### PythonConnection Constructor Source: https://github.com/intel/mfd-connect/blob/main/README.md This section details the constructor parameters for the PythonConnection class, which is used to establish RPyC connections to a remote host. ```APIDOC ## PythonConnection Constructor ### Description Initializes a PythonConnection object to establish an RPyC connection to a remote host. This class utilizes `rpyc_classic.py` for its server implementation. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ip** (Union["IPAddress", str]) - Required - IP Address of the remote host. - **port** (int) - Optional - TCP port to be used for establishing connection. Defaults to the port from the module. - **path_extension** (str) - Optional - PATH environment variable extension for calling commands. - **connection_timeout** (int) - Optional - Timeout value in seconds. If a timeout occurs without a response from the server, `AsyncResultTimeout` is raised. Defaults to 360. - **default_timeout** (int | None) - Optional - Set the default_timeout property. - **retry_timeout** (Optional[int]) - Optional - Time in seconds for connection retries. - **retry_time** (int) - Optional - Time in seconds between connection retries. Defaults to 5. - **enable_bg_serving_thread** (bool) - Optional - Set to True to activate the background serving thread, False otherwise. Defaults to True. - **model** (Optional["BaseModel"]) - Optional - Pydantic model of the connection. - **enable_deploy** (bool) - Optional - Determines whether to check the SHA of the remote PP and deploy the responder if needed. Defaults to False. - **deploy_username** (str) - Optional - Username used for deployment of PP onto the remote host. - **deploy_password** (str) - Optional - Password used for deployment of PP onto the remote host. - **share_url** (str) - Optional - Location of the PP tarball on the fileserver. - **share_username** (str) - Optional - Username for downloading the PP tarball from the fileserver. - **share_password** (str) - Optional - Password for downloading the PP tarball from the fileserver. - **ssl_keyfile** (str | None) - Optional - Path to the SSL key file. If not provided, the client will run without SSL. - **ssl_certfile** (str | None) - Optional - Path to the SSL certificate file. If not provided, the client will run without SSL. ### Request Example ```python from mfd_connect import PythonConnection connection = PythonConnection("192.168.1.100", port=12345, connection_timeout=60) ``` ### Response #### Success Response (None) This is a constructor, it does not return a value directly. #### Response Example N/A ``` -------------------------------- ### Restart and Shutdown Platform Source: https://github.com/intel/mfd-connect/blob/main/README.md Methods to reboot or shut down the remote platform. `restart_platform` uses `shutdown -r`, and `shutdown_platform` uses `shutdown -s`. ```python from mfd_connect.connection import SerialConnection connection = SerialConnection(port="/dev/ttyS0") # To restart the platform: # connection.restart_platform() # To shut down the platform: # connection.shutdown_platform() ``` -------------------------------- ### Permissions Utility Functions Source: https://github.com/intel/mfd-connect/blob/main/README.md Utility functions for managing file and directory permissions and ownership. These functions are located in `util/rpc_permission_utils.py`. ```APIDOC ## UTILS /rpc_permission_utils.py ### Description Provides utilities for changing file/directory permissions and ownership. ### change_mode #### Description Changes the access permissions of a file or directory. #### Parameters - **connection** (Connection) - Required - The connection object. - **path** (Path | CustomPath | str) - Required - The path to the file or directory. - **mode** (int) - Required - The operating-system mode bitfield (e.g., 0o775). #### Request Example ```python change_mode(connection=my_connection, path='/path/to/file.txt', mode=0o755) ``` ### change_owner #### Description Changes the ownership of a file or directory. #### Parameters - **connection** (Connection) - Required - The connection object. - **path** (Path | CustomPath | str) - Required - The path to the file or directory. - **user** (str) - Required - The username to transfer ownership to. - **group** (str) - Required - The group to transfer ownership to. #### Request Example ```python change_owner(connection=my_connection, path='/path/to/file.txt', user='newuser', group='newgroup') ``` ### Notes - Both `change_mode` and `change_owner` will raise an Exception if the specified path does not exist. ``` -------------------------------- ### Directory Creation: `mkdir()` Method Source: https://github.com/intel/mfd-connect/blob/main/mfd_connect/pathlib/PATHLIB.md The `mkdir()` method creates a new directory at the specified path. It supports creating parent directories if they don't exist and can optionally ignore errors if the directory already exists. ```python mkdir(mode=0o777, parents: bool = False, exist_ok: bool = False) """ Create a new directory at this path. :param mode: If mode is given, it is combined with the process’ umask value to determine the file mode and access flag :param parents: If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command). If parents is false (the default), a missing parent raises FileNotFoundError. :param exist_ok: If exist_ok is false (the default), FileExistsError is raised if the target directory already exists. If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file. :raise FileNotFoundError: If parents is false (the default), a missing parent raises FileNotFoundError. :raise FileExistsError: If the path already exists, FileExistsError is raised. """ ``` -------------------------------- ### Pathlib Additional Operations Source: https://github.com/intel/mfd-connect/blob/main/README.md Provides extended utility functions beyond the standard pathlib library for path operations. ```APIDOC ## UTILS /pathlib_utils.py ### Description Offers additional path operations that are not covered by the standard pathlib library. ### append_file #### Description Appends content to a specified file. #### Parameters - **connection** (Connection) - Required - The connection object. - **file_path** (Path | CustomPath | str) - Required - The path to the file. - **content** (str) - Required - The content to append to the file. #### Request Example ```python append_file(connection=my_connection, file_path='/path/to/file.txt', content='New content to append.') ``` ### remove_all_from_path #### Description Removes a path and all its contents (files and directories). #### Parameters - **connection** (Connection) - Required - The connection object. - **path** (Path | CustomPath | str) - Required - The path to remove. #### Request Example ```python remove_all_from_path(connection=my_connection, path='/path/to/remove/') ``` ``` -------------------------------- ### File Creation: `touch()` Method Source: https://github.com/intel/mfd-connect/blob/main/mfd_connect/pathlib/PATHLIB.md The `touch(mode=0o666, exist_ok=True)` method creates a file at the given path if it does not already exist. It allows specifying the file mode and whether to raise an error if the file already exists. ```python touch(mode=0o666, exist_ok: bool = True): """Create this file with the given access mode, if it doesn't exist.""" ``` -------------------------------- ### SerialConnection: Connect to Serial Devices via Host Source: https://github.com/intel/mfd-connect/blob/main/README.md Establishes a connection to a serial device by first connecting to a host, redirecting the serial device through netcat, and then creating a TelnetConnection to the redirected port. Supports Veloce emulation with a specific parameter and allows setting baudrate. Logs can be captured using `serial_logs_path`. Disconnection stops the netcat server and closes the connection. ```python from mfd_connect.connections.serial import SerialConnection # Example of initializing SerialConnection serial_conn = SerialConnection(host='your_host_ip', port=23, serial_port='/dev/ttyS0', baudrate=9600, is_veloce=False, serial_logs_path='/path/to/serial.log') # Example of executing a command # output = serial_conn.execute_command('ls -l') # Example of disconnecting # serial_conn.disconnect() ``` -------------------------------- ### Enable Sudo for Command Execution Source: https://github.com/intel/mfd-connect/blob/main/README.md Enables sudo privileges for subsequent command executions on POSIX systems. This affects methods like execute_command and start_process. Sudo is disabled by default. ```python connection.enable_sudo() # Now commands executed via execute_command or start_process will use sudo ``` -------------------------------- ### Background Command Execution (SSHConnection) Source: https://github.com/intel/mfd-connect/blob/main/README.md Techniques for executing commands in the background using SSHConnection. ```APIDOC ## Background Command Execution (SSHConnection) ### Description Explains how to execute commands in the background using `SSHConnection`, ensuring process persistence. ### How To There are two primary options for triggering background commands: 1. **`start_process`**: Saving the returned `SSHProcess` object will keep the process alive until it's garbage collected. 2. **`execute_command` with `&`**: Appending `&` to a command (on POSIX systems) starts a background process but may cause it to be killed immediately if not handled correctly. To ensure a background process persists on the OS, redirection of its standard output stream is required. - **Recommended Method**: Use `start_process` to get an `SSHProcess` object that allows explicit control over the process lifecycle, including stopping it when necessary. This is the preferred approach for managing background tasks. - **Alternative (with Redirection)**: If using `execute_command`, redirect the output stream (e.g., `>/dev/null` or by setting `discard_stdout=True` in `execute_command`) to prevent the OS from killing the process prematurely. This method requires manual stream redirection. ``` -------------------------------- ### WinRmConnection: Establish Connection via pywinrm Source: https://github.com/intel/mfd-connect/blob/main/README.md Connects to a server using the Windows Remote Management (WinRM) protocol via the `pywinrm` library. Requires IP address, username, and password. Note that several `execute_command` parameters and stream-related APIs are not functional for WinRM. ```python from mfd_connect.connections.winrm import WinRmConnection # Example initialization # winrm_conn = WinRmConnection(ip='server_ip', username='user', password='password') ```