### CLI usage examples for mssh-putty and msftp-putty Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/mputty.md Shows how to invoke the PuTTY-based clients from the command line. The mssh-putty example connects via SSH, while the msftp-putty example uses SFTP with a remote file path. Both require a .ppk identity file. ```text bin/mssh-putty.cmd -i my-key.ppk -u dev -z us-west-2a ec2-user@i-0b01816d5c99826d8 bin/msftp-putty.cmd -i my-key.ppk -u dev ec2-user@i-0b01816d5c99826d8:my-file ``` -------------------------------- ### Install ec2-connect-cli from source Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.rst After obtaining the ec2instanceconnectcli directory structure, run these commands to install the package from source. ```bash $ cd $ python setup.py install ``` -------------------------------- ### Example: basic execution of run_command() Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Shows how to call run_command() with a simple command and print the return code. The example expects the output '0' for a successful command. ```python cli = EC2InstanceConnectCLI(None, None, None, None) code = cli.run_command("echo ok") print(code) # 0 ``` -------------------------------- ### Example: public key in OpenSSH format Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/key_utils.md Example showing how to generate a key and serialize the public key in OpenSSH format, the CLI's main path. ```python from ec2instanceconnectcli import key_utils key = key_utils.generate_key(2048) pub = key_utils.serialize_key(key, encoding='OpenSSH').decode('utf-8') # 'ssh-rsa AAAAB3NzaC1yc2E...' ``` -------------------------------- ### Example - sftp with a file target Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCommand.md Shows how to instantiate EC2InstanceConnectCommand for an sftp command with a file target on the bundle, and prints the generated command. ```python bundles = [{'username': 'ec2-user', 'host_info': '54.245.189.134', 'file': 'my-file'}] cmd = EC2InstanceConnectCommand("sftp", bundles, "/tmp/key", "-b batch.txt", "", logger) print(cmd.get_command()) # sftp -o "IdentitiesOnly=yes" -i /tmp/key -b batch.txt ec2-user@54.245.189.134:my-file ``` -------------------------------- ### Example: calling the module directly (equivalent to mssh) Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/mops.md Shows how to invoke mops.main with 'ssh' mode, equivalent to running the mssh binary. The example command connects to an instance and runs 'ls -la'. ```python import sys from ec2instanceconnectcli import mops sys.exit(mops.main("ssh", "ssh")) # e.g. ./bin/mssh ec2-user@i-0b01816d5c99826d8 -u dev -z us-west-2a -r us-west-2 ls -la ``` -------------------------------- ### Install documentation dependencies Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.md Install the dependencies required for generating Sphinx documentation. ```bash pip install -r requirements-docs.txt ``` -------------------------------- ### Example creating a botocore session Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Shows how to call _get_botocore_session with a profile and region, then create an EC2 client from the session. This example is from the documentation for _get_botocore_session. ```python session = EC2InstanceConnectCLI._get_botocore_session( profile_name="beta", region="us-west-2") client = session.create_client('ec2') ``` -------------------------------- ### Full lifecycle example with error awareness Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectKey.md Example showing how to use the key for an SSH connection and then delete the object to trigger automatic temp file removal. Includes an assertion to verify the file is gone. ```python import os from ec2instanceconnectcli.EC2InstanceConnectKey import EC2InstanceConnectKey key = EC2InstanceConnectKey(logger) priv_file = key.get_priv_key_file() # Use the key for an ssh connection here... # Either let the object be garbage-collected (temp file removed automatically), del key assert not os.path.exists(priv_file) ``` -------------------------------- ### Install ec2instanceconnectcli with pip Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.rst Install the ec2-connect-cli package using pip. Use this command in a virtual environment or when you have permission to install packages. ```bash $ pip install ec2instanceconnectcli ``` -------------------------------- ### Install package dependencies Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.md Install the required Python packages listed in requirements.txt using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Example flow used by mops.main Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Shows the exact sequence to invoke the CLI programmatically: create a logger, parse instance bundles and flags, build the key and command objects, then call invoke_command. This example is from the documentation for invoke_command. ```python from ec2instanceconnectcli.EC2InstanceConnectCLI import EC2InstanceConnectCLI from ec2instanceconnectcli.EC2InstanceConnectKey import EC2InstanceConnectKey from ec2instanceconnectcli.EC2InstanceConnectCommand import EC2InstanceConnectCommand from ec2instanceconnectcli.EC2InstanceConnectLogger import EC2InstanceConnectLogger logger = EC2InstanceConnectLogger(debug=False) instance_bundles, flags, program_command = [...] # from input_parser.parseargs cli_key = EC2InstanceConnectKey(logger.get_logger()) cli_command = EC2InstanceConnectCommand("ssh", instance_bundles, cli_key.get_priv_key_file(), flags, program_command, logger.get_logger()) cli = EC2InstanceConnectCLI(instance_bundles, cli_key.get_pub_key(), cli_command, logger.get_logger()) return cli.invoke_command() ``` -------------------------------- ### Example - basic ssh command Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCommand.md Shows how to instantiate EC2InstanceConnectCommand for an ssh command with flags and a remote command, and prints the generated command. ```python from ec2instanceconnectcli.EC2InstanceConnectCommand import EC2InstanceConnectCommand import logging logger = logging.getLogger('EC2InstanceConnect') bundles = [{'username': 'ec2-user', 'host_info': '54.245.189.134'}] cmd = EC2InstanceConnectCommand("ssh", bundles, "/tmp/key", "-p 2222", "ls -la", logger) print(cmd.get_command()) # ssh -o "IdentitiesOnly=yes" -i /tmp/key -p 2222 ec2-user@54.245.189.134 ls -la ``` -------------------------------- ### Example: resolving host info from an instance ID with call_ec2() Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Shows how to create an EC2InstanceConnectCLI instance with a bundle containing an instance ID and call call_ec2() to populate 'host_info' and 'zone'. The example prints the resolved public/private IP and availability zone. ```python from ec2instanceconnectcli.EC2InstanceConnectCLI import EC2InstanceConnectCLI bundles = [{ 'profile': 'dev', 'instance_id': 'i-0b01816d5c99826d8', 'region': 'us-west-2', 'zone': None, 'username': 'ec2-user', 'target': None, }] # host_info is filled by call_ec2() from DescribeInstances: cli = EC2InstanceConnectCLI(bundles, pub_key, cli_command, logger) cli.call_ec2() print(bundles[0]['host_info']) # public IP, else private IP print(bundles[0]['zone']) # e.g. us-west-2a ``` -------------------------------- ### Install ec2instanceconnectcli with sudo pip Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.rst Install the ec2-connect-cli package using sudo when not installing in a virtualenv. This may be required for system-wide installation. ```bash $ sudo pip install ec2instanceconnectcli ``` -------------------------------- ### Example: password-protected private key with error handling Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/key_utils.md Example showing error handling for OpenSSH private key serialization and password-protected PEM serialization. ```python key = key_utils.generate_key(2048) try: bad = key_utils.serialize_key(key, encoding='OpenSSH', return_private=True) except AssertionError as e: print(str(e)) # 'Private keys cannot be serialized in OpenSSH encoding' priv = key_utils.serialize_key(key, encoding='PEM', return_private=True, password=b'secret') ``` -------------------------------- ### Basic usage of EC2InstanceConnectKey Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectKey.md Example showing how to instantiate the class with a logger and access the public key and private key file path. The private key file is created with mode 0600. ```python from ec2instanceconnectcli.EC2InstanceConnectKey import EC2InstanceConnectKey from ec2instanceconnectcli.EC2InstanceConnectLogger import EC2InstanceConnectLogger logger = EC2InstanceConnectLogger(debug=True) key = EC2InstanceConnectKey(logger.get_logger()) print(key.get_pub_key()) # 'ssh-rsa AAAA...' print(key.get_priv_key_file()) # '/tmp/tmpXXXX' (mode 0600) ``` -------------------------------- ### Example: error handling for run_command() Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Shows how to catch the ValueError raised when run_command() is called with None. The example prints the error message 'Must provide a command'. ```python try: cli.run_command(None) except ValueError as e: print(str(e)) # "Must provide a command" ``` -------------------------------- ### Example: sftp mode with error handling wrapper Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/mops.md Shows how to call mops.main in sftp mode and catch SystemExit to handle parse errors and CLI failures. ```python from ec2instanceconnectcli import mops try: code = mops.main("sftp", "sftp") except SystemExit as e: # parse errors print the message + help; CLI failures print 'Failed with:\n' print("mops exited with code", e.code) ``` -------------------------------- ### Typical SSH usage of parseargs Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/input_parser.md Shows how to call parseargs from an entry point with an argparse parser. The example parses arguments including an instance ID and a target like 'ec2-user@i-...' and prints the resulting bundles, flags, and command. The output shows the bundle dict with username and target fields. ```python import argparse from ec2instanceconnectcli import input_parser parser = argparse.ArgumentParser() parser.add_argument('-t', '--instance_id', default='') parser.add_argument('-u', '--profile', default=None) parser.add_argument('-r', '--region', default=None) parser.add_argument('-z', '--zone', default=None) args = parser.parse_known_args(['-t', 'i-0b01816d5c99826d8', 'ec2-user@i-0b01816d5c99826d8', 'ls', '-la']) bundles, flags, command = input_parser.parseargs(args, mode='ssh') print(bundles) # [{'profile': None, 'instance_id': 'i-0b01816d5c99826d8', # 'region': None, 'zone': None, # 'username': 'ec2-user', 'target': None}] print(flags) # '' print(command) # 'ls -la' ``` -------------------------------- ### Handling the 'no hostname' failure case Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/ec2_util.md Demonstrates using a mock session to simulate a response with no DNS or IP fields, causing get_instance_data to print 'No hostname or IPs found' and exit with status 8. The example catches SystemExit and prints the exit code. ```python import sys from unittest.mock import Mock from ec2instanceconnectcli import ec2_util session = Mock() session.create_client.return_value.describe_instances.return_value = { 'Reservations': [{'Instances': [{'Placement': {'AvailabilityZone': 'us-west-2a'}}]}] } try: ec2_util.get_instance_data(session, "i-0b01816d5c99826d8") except SystemExit as e: # prints "No hostname or IPs found" and exits with status 8 print("exit code:", e.code) ``` -------------------------------- ### Upgrade ec2instanceconnectcli with pip Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.rst Upgrade an existing ec2-connect-cli installation to the latest version. ```bash $ pip install --upgrade ec2instanceconnectcli ``` -------------------------------- ### Log sink customization Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectLogger.md Removes the default StreamHandler and adds a FileHandler to write log messages to 'mssh.log'. This example shows how to customize the log destination. ```python import logging from ec2instanceconnectcli.EC2InstanceConnectLogger import EC2InstanceConnectLogger tui = EC2InstanceConnectLogger() log = tui.get_logger() # currently has the default StreamHandler log.handlers.clear() # remove the default handler log.addHandler(logging.FileHandler('mssh.log')) cli = EC2InstanceConnectCLI(bundles, pub_key, cli_command, log) cli.invoke_command() # messages now go to mssh.log ``` -------------------------------- ### SFTP target with file and error handling Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/input_parser.md Shows parseargs in sftp mode with a target that includes a file (ec2-user@i-...:my-file). The example prints the file from the first bundle and catches AssertionError to handle parse failures. ```python try: bundles, flags, command = input_parser.parseargs( (args_namespace, ['ec2-user@i-0b01816d5c99826d8:my-file']), mode='sftp') print(bundles[0]['file']) # 'my-file' except AssertionError as e: print("parse failed:", e) ``` -------------------------------- ### Catch SystemExit from get_instance_data Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/errors.md Example of catching SystemExit when calling ec2_util.get_instance_data, inspecting e.code to handle exit codes 1, 7, or 8. ```python import sys from ec2instanceconnectcli import ec2_util try: info = ec2_util.get_instance_data(session, "i-0b01816d5c99826d8") except SystemExit as e: print("exited with", e.code) # 1, 7, or 8 sys.exit(e.code) ``` -------------------------------- ### call_ec2() Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Resolves instance information for each bundle in self.instance_bundles, setting zone and host_info fields. It calls the EC2 API to get instance data unless the target and zone are already set or the instance ID is empty. ```APIDOC ## call_ec2() ### Description Resolves instance information for every bundle that needs it. For each bundle, it sets `host_info` and `zone` based on the EC2 API response, skipping the API call when the target and zone are already set or when the instance ID is empty. ### Method call_ec2() ### Signature ```python def call_ec2(self): ``` ### Parameters None. Operates entirely on `self.instance_bundles`. ### Returns `None` — mutates each `instance_bundles` dict in place by adding `zone` and `host_info`. ### Throws `SystemExit` — `ec2_util.get_instance_data` calls `sys.exit(1)`, `sys.exit(7)`, or `sys.exit(8)` on AWS API errors / missing zone / missing hostname data. ### Example ```python from ec2instanceconnectcli.EC2InstanceConnectCLI import EC2InstanceConnectCLI bundles = [{ 'profile': 'dev', 'instance_id': 'i-0b01816d5c99826d8', 'region': 'us-west-2', 'zone': None, 'username': 'ec2-user', 'target': None, }] # host_info is filled by call_ec2() from DescribeInstances: cli = EC2InstanceConnectCLI(bundles, pub_key, cli_command, logger) cli.call_ec2() print(bundles[0]['host_info']) # public IP, else private IP print(bundles[0]['zone']) # e.g. us-west-2a ``` ``` -------------------------------- ### main(program, mode) Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/mops.md Entry point for the mssh and msftp clients. Parses command-line arguments, generates an ephemeral key, and invokes the EC2InstanceConnectCLI to connect to an instance. ```APIDOC ## main(program, mode) ### Description Entry point for the mssh and msftp clients. Parses command-line arguments, generates an ephemeral key, and invokes the EC2InstanceConnectCLI to connect to an instance. ### Method Function call ### Endpoint `mops.main(program, mode)` ### Parameters - **program** (basestring) - Required - Client binary to invoke: `'ssh'` or `'sftp'`. - **mode** (basestring) - Required - Operation identifier: `'ssh'` or `'sftp'`; drives the usage text and parsing behavior. ### Returns - **int** - Return code of the remote command (from `invoke_command`). ### Throws / Exits - `sys.exit(1)` in both catch blocks; the function never returns on failure. Errors from `invoke_command` are also already `sys.exit(1)`. ### Example ```python import sys from ec2instanceconnectcli import mops sys.exit(mops.main("ssh", "ssh")) # e.g. ./bin/mssh ec2-user@i-0b01816d5c99826d8 -u dev -z us-west-2a -r us-west-2 ls -la ``` ### Example (sftp mode with error handling wrapper) ```python from ec2instanceconnectcli import mops try: code = mops.main("sftp", "sftp") except SystemExit as e: # parse errors print the message + help; CLI failures print 'Failed with:\n' print("mops exited with code", e.code) ``` ``` -------------------------------- ### main(program, mode) Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/mputty.md Entry point for PuTTY-based clients. Parses arguments, reads the PPK identity file, extracts the public key, and invokes the EC2 Instance Connect CLI. Returns the remote command return code. ```APIDOC ## main(program, mode) ### Description Entry point for PuTTY-based clients (mssh-putty, msftp-putty). Parses command-line arguments, reads the required PPK identity file, extracts the public key, and invokes the EC2 Instance Connect CLI. Returns the remote command return code. ### Signature ```python def main(program, mode): ``` ### Parameters - **program** (basestring/str) - Required - Client program: `'putty -ssh'` or `'psftp'`. - **mode** (basestring/str) - Required - Operation identifier: `'ssh'` or `'sftp'`. ### Returns - **int** - Remote command return code. ### Exits / Throws - `sys.exit(1)` for invalid PPK files, parse failures, and invocation failures. - `sys.exit(2)` if `-i/--identity` is missing (argparse enforces required=True). ### Behavior 1. Builds argparse parser with mode-dependent usage text. 2. Registers flags: `-r/--region`, `-z/--zone`, `-i/--identity` (required), `-u/--profile` (default None), `-t/--instance_id` (default ''), `-d/--debug` (store_true). 3. Reads PPK file, verifies first line contains `"PuTTY-User-Key-File-"`, extracts public key from lines 4+. 4. Creates logger and parses remaining arguments. 5. Builds EC2InstanceConnectCommand with PPK file as key_file. 6. Instantiates EC2InstanceConnectCLI and invokes command. ### Example (CLI usage) ```text bin/mssh-putty.cmd -i my-key.ppk -u dev -z us-west-2a ec2-user@i-0b01816d5c99826d8 bin/msftp-putty.cmd -i my-key.ppk -u dev ec2-user@i-0b01816d5c99826d8:my-file ``` ### Example (programmatic call) ```python from ec2instanceconnectcli import mputty try: code = mputty.main("psftp", "sftp") except SystemExit as e: # e.g. "Not a valid Putty key." (exit 1), argparse missing -i (exit 2) print("exit:", e.code) ``` ``` -------------------------------- ### Connect to an instance by DNS name as user and run a command Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.rst Use mssh to connect as a specific user to an instance identified by DNS name and run the 'ls' command. ```bash $ mssh my-user@ec2-[ec2 IP].us-east-1.compute.amazonaws.com -t [instance id] ls ``` -------------------------------- ### Run sftp against instance using AWS CLI profile with msftp Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/doc/source/README.rst Runs sftp against an instance using the AWS CLI profile 'beta' and transfers a file. ```default $ msftp -pr beta [instance id]:my-file ``` -------------------------------- ### Initial instance bundle dict construction Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/types.md Shows the initial schema for an instance bundle dict, built at input_parser.py:62. Fields are populated from parsed arguments; later stages add username, target, file, session, and host_info. ```python instance_bundles = [ { 'profile': args[0].profile, 'instance_id': args[0].instance_id, 'region': args[0].region, 'zone': args[0].zone } ] ``` -------------------------------- ### Constructor signature of EC2InstanceConnectCommand Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCommand.md Shows the __init__ method signature with parameters for program, instance_bundles, key_file, flags, program_command, and logger. ```python def __init__(self, program, instance_bundles, key_file, flags, program_command, logger): ``` -------------------------------- ### EC2InstanceConnectCommand.__init__ Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCommand.md Constructor that stores all arguments as attributes for later use in command generation. ```APIDOC ## EC2InstanceConnectCommand.__init__ ### Description Initializes the command generator with the client program, instance bundles, key file, flags, program command, and logger. ### Method Constructor ### Signature ```python def __init__(self, program, instance_bundles, key_file, flags, program_command, logger): ``` ### Parameters - **program** (basestring) - Required - Client program to invoke: `'ssh'`, `'sftp'`, `'scp'`, or `'putty -ssh'` / `'psftp'`. - **instance_bundles** (list of dicts) - Required - Per-instance bundle dicts. - **key_file** (basestring) - Required - Private key file path (`-i` argument). - **flags** (basestring) - Required - Program-specific flags extracted from the raw command, space-separated; may be `''`. - **program_command** (basestring) - Required - Ad-hoc remote command (ssh) or file list (sftp); may be `''`. - **logger** (logging.Logger) - Required - Logger from `EC2InstanceConnectLogger.get_logger()`. ### Notes All arguments are stored as attributes: `self.logger`, `self.program`, `self.instance_bundles`, `self.key_file`, `self.flags`, `self.program_command`. ``` -------------------------------- ### Programmatic call to mputty.main with error handling Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/mputty.md Shows how to call mputty.main from Python, catching SystemExit to handle errors such as 'Not a valid Putty key.' (exit 1) or argparse missing -i (exit 2). ```python from ec2instanceconnectcli import mputty try: code = mputty.main("psftp", "sftp") except SystemExit as e: # e.g. "Not a valid Putty key." (exit 1), argparse missing -i (exit 2) print("exit:", e.code) ``` -------------------------------- ### Basic call to push_public_key Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/key_publisher.md Shows how to create a botocore session and call push_public_key with an instance ID, user, public key, and availability zone. The function returns None and discards the API response. ```python from ec2instanceconnectcli.EC2InstanceConnectCLI import EC2InstanceConnectCLI from ec2instanceconnectcli import key_publisher session = EC2InstanceConnectCLI._get_botocore_session(profile_name="dev", region="us-west-2") pub_key = "ssh-rsa AAAAB3NzaC1yc2E... user@host" key_publisher.push_public_key( session, instance_id="i-0b01816d5c99826d8", user="ec2-user", pub_key=pub_key, target_zone="us-west-2a", ) ``` -------------------------------- ### Error handling for push_public_key Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/key_publisher.md Demonstrates catching SystemExit when the client creation fails. The function prints 'Error while trying to push the public key:\n' plus the exception message and exits with code 1. ```python import sys from unittest.mock import Mock from ec2instanceconnectcli import key_publisher bad_session = Mock() bad_session.create_client.side_effect = Exception("region not found") try: key_publisher.push_public_key(bad_session, "i-0b01816d5c99826d8", "ec2-user", "ssh-rsa AAAA", "us-west-2a") except SystemExit as e: # prints "Error while trying to push the public key:\nregion not found" print("exit code:", e.code) ``` -------------------------------- ### handle_keys() Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Pushes the public key to each instance through the EC2 Instance Connect service. It skips bundles with an empty instance ID (hostname-only targets). ```APIDOC ## handle_keys() ### Description Pushes `self.pub_key` to each instance through the EC2 Instance Connect service. For bundles with a non-empty `instance_id`, calls `key_publisher.push_public_key(session, bundle['instance_id'], bundle['username'], self.pub_key, bundle['zone'])`; bundles with an empty `instance_id` (hostname-only targets) are skipped with a debug log. ### Method handle_keys() ### Signature ```python def handle_keys(self): ``` ### Parameters None. ### Returns `None`. ### Throws `SystemExit` — `key_publisher.push_public_key` calls `sys.exit(1)` when the `ec2-instance-connect` client cannot be created or when `send_ssh_public_key` fails. ``` -------------------------------- ### Build Sphinx documentation Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.md Build the HTML documentation from the generated reStructuredText files, specifying the desired output directory. ```bash sphinx-build ./doc/source [desired output directory] ``` -------------------------------- ### EC2InstanceConnectCLI.__init__ Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Constructor for the EC2InstanceConnectCLI class. It stores the provided instance bundles, public key, CLI command builder, and logger as instance attributes. ```APIDOC ## EC2InstanceConnectCLI.__init__ ### Description Constructor for the EC2InstanceConnectCLI class. It stores the provided instance bundles, public key, CLI command builder, and logger as instance attributes. ### Method Constructor ### Signature ```python def __init__(self, instance_bundles, pub_key, cli_command, logger): ``` ### Parameters - **instance_bundles** (list of dicts) - Required - List of dicts providing DNS name, zone, etc. for EC2 instances. Schema documented in types.md. `None` is tolerated at construction but `invoke_command()` will fail. - **pub_key** (basestring/str) - Required - SSH public key body (OpenSSH format) to push to the instance(s). - **cli_command** (EC2InstanceConnectCommand) - Required - Command builder used to produce the shell command via `get_command()`. - **logger** (logging.Logger) - Required - Logger obtained from `EC2InstanceConnectLogger.get_logger()`. ### Behavior Stores all four arguments as instance attributes: `self.instance_bundles`, `self.pub_key`, `self.logger`, `self.cli_command`. ``` -------------------------------- ### Run sftp with AWS CLI profile and transfer file Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.rst Use msftp with the 'otherprofile' AWS CLI profile to transfer 'my-file' to an instance identified by its instance ID. ```bash $ msftp -pr otherprofile [instance id]:my-file ``` -------------------------------- ### Connect to an instance and open a shell Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.rst Use the mssh command to connect to an EC2 instance by its instance ID and open a shell. ```bash $ mssh [instance id] ``` -------------------------------- ### Basic call to get_instance_data Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/ec2_util.md Shows how to create a botocore session using EC2InstanceConnectCLI._get_botocore_session and call get_instance_data to retrieve instance info. Prints the availability zone and the public IP (or private IP if public is None). ```python from ec2instanceconnectcli.EC2InstanceConnectCLI import EC2InstanceConnectCLI from ec2instanceconnectcli import ec2_util session = EC2InstanceConnectCLI._get_botocore_session(profile_name="dev", region="us-west-2") info = ec2_util.get_instance_data(session, "i-0b01816d5c99826d8") print(info.availability_zone) # us-west-2a print(info.public_ip or info.private_ip) ``` -------------------------------- ### Create instance_info Namespace in ec2_util.py Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/types.md Constructs an argparse.Namespace with instance details (public/private DNS names, IPs, availability zone). Returned by ec2_util.get_instance_data and consumed by EC2InstanceConnectCLI.call_ec2, which reads availability_zone, public_ip, and private_ip. ```python instance_info = Namespace(public_dns_name=public_dns_name, private_dns_name=private_dns_name, public_ip=public_ip, private_ip=private_ip, availability_zone=availability_zone) ``` -------------------------------- ### Module constants: DEFAULT_INSTANCE and DEFAULT_PROFILE Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/mputty.md Defines the default values used for the -t/--instance_id and -u/--profile argparse arguments. DEFAULT_INSTANCE is an empty string, DEFAULT_PROFILE is None. ```python DEFAULT_INSTANCE = '' DEFAULT_PROFILE = None ``` -------------------------------- ### EC2InstanceConnectKey(logger) Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectKey.md Constructor that eagerly generates a 2048-bit RSA SSH keypair, writes the private key to a temporary file with mode 0600, and stores the public key and temp file handle. ```APIDOC ## EC2InstanceConnectKey(logger) ### Description Generates a 2048-bit RSA SSH keypair for the CLI session. Writes the private key to a temporary file on disk with permissions 0600 (read/write by owner only) and exposes the public key and private key file path. ### Constructor ```python def __init__(self, logger): ``` ### Parameters - **logger** (`logging.Logger`) - Required - Logger used for debug messages (e.g. from `EC2InstanceConnectLogger.get_logger()`). ### Throws - `AssertionError` - only from `serialize_key` interplay; under normal use this constructor does not raise. Filesystem errors from key writing propagate as-is. ### Example ```python from ec2instanceconnectcli.EC2InstanceConnectKey import EC2InstanceConnectKey from ec2instanceconnectcli.EC2InstanceConnectLogger import EC2InstanceConnectLogger logger = EC2InstanceConnectLogger(debug=True) key = EC2InstanceConnectKey(logger.get_logger()) print(key.get_pub_key()) # 'ssh-rsa AAAA...' print(key.get_priv_key_file()) # '/tmp/tmpXXXX' (mode 0600) ``` ``` -------------------------------- ### EC2InstanceConnectCommand.get_command() Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCommand.md Generates and returns the full command string for the client program, including identity file, flags, targets, and optional remote command or file list. ```APIDOC ## EC2InstanceConnectCommand.get_command() ### Description Generates the full command string by combining the program, identity file, flags, targets, and program command. Logs the resulting command at debug level. ### Method Instance method ### Signature ```python def get_command(self): ``` ### Parameters None (uses instance attributes). ### Returns - **str** - The generated command, e.g. `ssh -o "IdentitiesOnly=yes" -i /tmp/tmpXXXX ec2-user@54.245.189.134 ls`. ### Throws - `IndexError`/`KeyError` if `instance_bundles` is empty or missing bundle keys; relies on the caller to have populated bundles via `input_parser.parseargs` and `EC2InstanceConnectCLI.call_ec2()` first. ### Build Order 1. `'{0} -o "IdentitiesOnly=yes" -i {1}'.format(self.program, self.key_file)` — protocol and identity file. 2. If `len(self.flags) > 0`, appends `' {0}'.format(self.flags)`. 3. Appends `' {0}'.format(self._get_target(self.instance_bundles[0]))` — first target. 4. If `len(self.program_command) > 0`, appends the program command as-is. 5. If `len(self.instance_bundles) > 1`, appends `' {0}'.format(self._get_target(self.instance_bundles[1]))` — second target (used for multiple-instance commands such as scp). ### Example ```python from ec2instanceconnectcli.EC2InstanceConnectCommand import EC2InstanceConnectCommand import logging logger = logging.getLogger('EC2InstanceConnect') bundles = [{'username': 'ec2-user', 'host_info': '54.245.189.134'}] cmd = EC2InstanceConnectCommand("ssh", bundles, "/tmp/key", "-p 2222", "ls -la", logger) print(cmd.get_command()) # ssh -o "IdentitiesOnly=yes" -i /tmp/key -p 2222 ec2-user@54.245.189.134 ls -la ``` ``` -------------------------------- ### get_instance_data(session, instance_id) Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/ec2_util.md Fetches instance data (DNS names, IPs, availability zone) for a single EC2 instance using the DescribeInstances API. Returns an argparse.Namespace with the instance attributes, or exits with a specific code on failure. ```APIDOC ## get_instance_data(session, instance_id) ### Description Fetches public/private DNS names, public/private IPs, and the availability zone of a single EC2 instance using the AWS EC2 DescribeInstances API. Returns an `argparse.Namespace` with the instance attributes. ### Method Function call ### Endpoint N/A (SDK function) ### Parameters - **session** (botocore.session.Session) - Required - Botocore session used to create the `ec2` client (must have credentials configured). - **instance_id** (basestring/str) - Required - Instance ID of the instance, e.g. `'i-0b01816d5c99826d8'`. ### Returns `argparse.Namespace` with attributes: - **public_dns_name** (str | None) - Instance `PublicDnsName` - **private_dns_name** (str | None) - Instance `PrivateDnsName` - **public_ip** (str | None) - Instance `PublicIpAddress` - **private_ip** (str | None) - Instance `PrivateIpAddress` - **availability_zone** (str) - Instance placement availability zone ### Exits / Errors - On any exception from client creation or API call: prints `str(e)` and calls `sys.exit(1)`. - If `availability_zone` is empty: prints `Instance zone information not found` and calls `sys.exit(7)`. - If none of the four DNS/IP values are present: prints `No hostname or IPs found` and calls `sys.exit(8)`. - Exceptions are never propagated to the caller. ### Example ```python from ec2instanceconnectcli.EC2InstanceConnectCLI import EC2InstanceConnectCLI from ec2instanceconnectcli import ec2_util session = EC2InstanceConnectCLI._get_botocore_session(profile_name="dev", region="us-west-2") info = ec2_util.get_instance_data(session, "i-0b01816d5c99826d8") print(info.availability_zone) # us-west-2a print(info.public_ip or info.private_ip) ``` ``` -------------------------------- ### Generate module documentation with sphinx-apidoc Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.md Generate reStructuredText files for the ec2instanceconnectcli module using sphinx-apidoc. ```bash sphinx-apidoc -o doc/source ec2instanceconnectcli ``` -------------------------------- ### Function signature: main(program, mode) Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/mputty.md Signature of the main function in mputty.py. It takes the client program string ('putty -ssh' or 'psftp') and the mode ('ssh' or 'sftp'). ```python def main(program, mode): ``` -------------------------------- ### Run mssh script Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.md Run the mssh script with standard UNIX pathing, specifying the user@host, profile, instance ID, and availability zone. ```bash ./bin/mssh ec2-user@ec2-54-245-189-134.us-west-2.compute.amazonaws.com -pr dev -t i-0b01816d5c99826d8 -z us-west-2a ``` -------------------------------- ### EC2InstanceConnectCommand._get_target(instance_bundle) Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCommand.md Static method that determines the connection target (and potentially the SFTP file target) for one instance bundle dict. ```APIDOC ## EC2InstanceConnectCommand._get_target(instance_bundle) ### Description Builds the target string in the form `user@host[:file]` from an instance bundle dict. If `host_info` is truthy, includes the `user@` prefix; if `file` is truthy, appends `:file`. ### Method Static method ### Signature ```python @staticmethod def _get_target(instance_bundle): ``` ### Parameters - **instance_bundle** (dict) - Required - Single instance bundle; must contain `username`, optionally `host_info` and `file`. ### Returns - **basestring** (str) - Target in the form `user@host[:file]`. ### Throws - `KeyError` if `username` is missing from the bundle. ### Behavior - If `instance_bundle.get('host_info', None)` is truthy, builds `'{0}@{1}'.format(instance_bundle['username'], instance_bundle['host_info'])`; otherwise the user@ prefix is omitted. - If `instance_bundle.get('file', None)` is truthy, appends `'{0}:{1}'.format(target, instance_bundle['file'])` and strips a leading `':'`. ### Example ```python bundles = [{'username': 'ec2-user', 'host_info': '54.245.189.134', 'file': 'my-file'}] cmd = EC2InstanceConnectCommand("sftp", bundles, "/tmp/key", "-b batch.txt", "", logger) print(cmd.get_command()) # sftp -o "IdentitiesOnly=yes" -i /tmp/key -b batch.txt ec2-user@54.245.189.134:my-file ``` ``` -------------------------------- ### get_priv_key_file method Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectKey.md Method signature for retrieving the path of the temporary file containing the private key. The file is deleted when the object is garbage-collected. ```python def get_priv_key_file(self): ``` -------------------------------- ### Connect to an instance by DNS name as user and run command with mssh Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/doc/source/README.rst Connects to an EC2 instance using its DNS name, specifying a user and running a command. ```default $ mssh [my-user@ec2](mailto:my-user@ec2)-[ec2 IP].us-east-1.compute.amazonaws.com -t [instance id] ls ``` -------------------------------- ### handle_keys() method signature Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Signature of the handle_keys() method. It pushes self.pub_key to each instance via the EC2 Instance Connect service. Bundles with empty instance_id are skipped. May throw SystemExit on client creation or send_ssh_public_key failure. ```python def handle_keys(self): ``` -------------------------------- ### EC2InstanceConnectKey constructor Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectKey.md Constructor signature that eagerly generates the keypair. It stores the logger, generates a 2048-bit RSA key, serializes public and private keys, and writes the private key to a temp file. ```python def __init__(self, logger): ``` -------------------------------- ### _get_botocore_session(profile_name=None, region=None) — static method Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Creates a botocore session with the CLI user agent and optional profile/region configuration. Returns the configured session. ```APIDOC ## _get_botocore_session(profile_name=None, region=None) — static method ### Description Creates a `botocore.session.Session` tagged with the CLI user agent. Sets `session.user_agent_name = 'aws-ec2-instance-connect-cli'` and `session.user_agent_version = CLI_VERSION` (from `ec2instanceconnectcli.__version__`), appending `'Botocore/'` to `user_agent_extra`. Then, per the documented credential precedence `# 1. set user passed profile. # 2. set user passed region. # 3. let botocore handle the rest.`, calls `session.set_config_variable('profile', profile_name)` only when a profile is given and `session.set_config_variable('region', region)` only when `region is not None`. ### Method _get_botocore_session(profile_name=None, region=None) ### Signature ```python @staticmethod def _get_botocore_session(profile_name=None, region=None): ``` ### Parameters - `profile_name` (string) - Optional - AWS config profile name (e.g. `dev`). - `region` (string) - Optional - AWS region name to set as session default (e.g. `us-west-2`). ### Returns - `botocore.session.Session`. ### Throws Nothing from this method itself; credential failures surface later on API calls. ### Example ```python session = EC2InstanceConnectCLI._get_botocore_session( profile_name="beta", region="us-west-2") client = session.create_client('ec2') ``` ``` -------------------------------- ### invoke_command() Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/EC2InstanceConnectCLI.md Runs the full orchestration pipeline: resolves instance metadata, pushes public keys, generates the command, and executes it. Returns the remote command's exit code or exits with code 1 on failure. ```APIDOC ## invoke_command() ### Description Runs the full orchestration pipeline: creates botocore sessions for each bundle, resolves instance metadata, pushes public keys, generates the command, and executes it. Returns the remote command's exit code or exits with code 1 on failure. ### Method invoke_command() ### Signature ```python def invoke_command(self): ``` ### Parameters None. Uses `self.instance_bundles`, `self.cli_command`, `self.logger`. ### Returns - `int` — return code of the remote command (propagated from `run_command`). ### Throws - `SystemExit(1)` on any failure; the original exception is never propagated. ### Example ```python from ec2instanceconnectcli.EC2InstanceConnectCLI import EC2InstanceConnectCLI from ec2instanceconnectcli.EC2InstanceConnectKey import EC2InstanceConnectKey from ec2instanceconnectcli.EC2InstanceConnectCommand import EC2InstanceConnectCommand from ec2instanceconnectcli.EC2InstanceConnectLogger import EC2InstanceConnectLogger logger = EC2InstanceConnectLogger(debug=False) instance_bundles, flags, program_command = [...] # from input_parser.parseargs cli_key = EC2InstanceConnectKey(logger.get_logger()) cli_command = EC2InstanceConnectCommand("ssh", instance_bundles, cli_key.get_priv_key_file(), flags, program_command, logger.get_logger()) cli = EC2InstanceConnectCLI(instance_bundles, cli_key.get_pub_key(), cli_command, logger.get_logger()) return cli.invoke_command() ``` ``` -------------------------------- ### Request parameters for send_ssh_public_key Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/key_publisher.md Builds the parameters dictionary for the send_ssh_public_key API call, mapping instance_id, user, pub_key, and target_zone to InstanceId, InstanceOSUser, SSHPublicKey, and AvailabilityZone. ```python params = { 'InstanceId': instance_id, 'InstanceOSUser': user, 'SSHPublicKey': pub_key, 'AvailabilityZone': target_zone } ``` -------------------------------- ### Run unit tests with pytest Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/README.md Run the unit tests using pytest. Ensure PYTHONPATH is set to the package top-level directory. ```bash python -m pytest ``` -------------------------------- ### Package-level constants in ec2instanceconnectcli/__init__.py Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/types.md Defines the package's public export surface: __version__, EnvironmentVariables, SCALAR_TYPES, and COMPLEX_TYPES. __version__ is consumed by EC2InstanceConnectCLI._get_botocore_session as the user agent version; the other constants are declared but have no in-tree consumers. ```python __version__ = '1.0.3' EnvironmentVariables = { 'ca_bundle': ('ca_bundle', 'AWS_CA_BUNDLE', None, None), 'output': ('output', 'AWS_DEFAULT_OUTPUT', 'json', None), } SCALAR_TYPES = set([ 'string', 'float', 'integer', 'long', 'boolean', 'double', 'blob', 'timestamp' ]) COMPLEX_TYPES = set(['structure', 'map', 'list']) ``` -------------------------------- ### parseargs function signature Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/input_parser.md Main entry point for parsing CLI arguments. Called from mops.main and mputty.main. Accepts a tuple from parse_known_args and a mode ('ssh' or 'sftp'). Returns a tuple of (instance_bundles, flags, command). ```python def parseargs(args, mode='ssh'): ``` -------------------------------- ### Function signature: get_instance_data(session, instance_id) Source: https://github.com/aws/aws-ec2-instance-connect-cli/blob/master/_autodocs/api-reference/ec2_util.md Defines the get_instance_data function that takes a botocore session and an instance ID, returning an argparse.Namespace with instance details. It exits with code 1 on API errors, 7 if the zone is empty, and 8 if no hostname or IP is found. ```python def get_instance_data(session, instance_id): ```