ssm-connect 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.4
2
+ Name: ssm-connect
3
+ Version: 1.0.0
4
+ Summary: Interactive CLI to connect to AWS EC2 via SSM or SSH-over-SSM, with keyword search and multi-session terminal launch.
5
+ Author-email: Your Name <you@example.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/yourusername/ssm-connect
8
+ Project-URL: Issues, https://github.com/yourusername/ssm-connect/issues
9
+ Project-URL: Source, https://github.com/yourusername/ssm-connect
10
+ Keywords: aws,ec2,ssm,ssh,cli,session-manager
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Topic :: System :: Systems Administration
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: boto3>=1.26.0
29
+ Dynamic: license-file
30
+
31
+ Interactive CLI to connect to AWS EC2 instances via:
32
+
33
+ SSM Session Manager (shell)
34
+
35
+ SSH over SSM (with your SSH key)
36
+
37
+ Multiple sessions in parallel (opens each in a new terminal)
38
+
39
+ Keyword search across Name/ID/all tag values
40
+
41
+ Simple, cross-platform, and secure by default.
42
+
43
+ Features
44
+ Search instances by keywords (matches Name, InstanceId, and all tag values)
45
+
46
+ Choose SSM or SSH-over-SSM per connection
47
+
48
+ Optional strict SSH host key checking (security toggle)
49
+
50
+ Opens each session in a new terminal window (Linux, macOS, Windows)
51
+
52
+ Uses your existing AWS credentials (SSO, profiles, env vars)
53
+
54
+ Validates SSH key path and permissions (Unix)
55
+
56
+ Requirements
57
+ AWS account permissions to use SSM Session Manager
58
+
59
+ Locally installed:
60
+
61
+ AWS CLI v2
62
+
63
+ SSM Session Manager plugin
64
+
65
+ OpenSSH client (ssh)
66
+
67
+ Python 3.8+
68
+
69
+ boto3 (installed automatically if using PyPI package)
70
+
71
+ On Linux/macOS, ensure a terminal emulator exists (e.g., gnome-terminal, xterm, or Terminal.app on macOS). On Windows, PowerShell or Windows Terminal recommended.
72
+
73
+ Install
74
+ From source:
75
+
76
+ Clone this repo and run the script with Python 3.
77
+
78
+ From PyPI (if published):
79
+
80
+ pip install ssm-connect
81
+
82
+ ssm-connect
83
+
84
+ Usage
85
+ Run the tool
86
+
87
+ Optionally enter keywords to filter instances (e.g., “prod web”)
88
+
89
+ Select an instance
90
+
91
+ Choose connection type:
92
+
93
+ SSM (interactive shell)
94
+
95
+ SSH over SSM (enter SSH key path and user)
96
+
97
+ For SSH, choose whether to enable strict host key checking
98
+
99
+ Each session opens in a new terminal; you can open more without restarting the tool
100
+
101
+ Notes
102
+ SSH over SSM uses AWS-StartSSHSession and does not require port 22 open in security groups.
103
+
104
+ Strict host key checking is disabled by default for convenience; enable it for production/security-sensitive use.
105
+
106
+ The tool does not print or store credentials; it inherits your AWS session from the environment/AWS CLI.
107
+
108
+ Troubleshooting
109
+ If “aws” or “ssh” not found: ensure AWS CLI v2 and OpenSSH are on PATH.
110
+
111
+ If SSO token expired: run aws sso login or refresh your Granted/SSO session.
112
+
113
+ If SSH key error: ensure the private key exists locally and has correct permissions (chmod 600 on Unix). Avoid cloud-only paths (e.g., OneDrive placeholders).
114
+
115
+ License
116
+ Apache License 2.0. See LICENSE for details.
117
+
118
+ Contributing
119
+ Issues and PRs are welcome. Please keep changes focused and add brief notes to the README when behavior changes.
@@ -0,0 +1,89 @@
1
+ Interactive CLI to connect to AWS EC2 instances via:
2
+
3
+ SSM Session Manager (shell)
4
+
5
+ SSH over SSM (with your SSH key)
6
+
7
+ Multiple sessions in parallel (opens each in a new terminal)
8
+
9
+ Keyword search across Name/ID/all tag values
10
+
11
+ Simple, cross-platform, and secure by default.
12
+
13
+ Features
14
+ Search instances by keywords (matches Name, InstanceId, and all tag values)
15
+
16
+ Choose SSM or SSH-over-SSM per connection
17
+
18
+ Optional strict SSH host key checking (security toggle)
19
+
20
+ Opens each session in a new terminal window (Linux, macOS, Windows)
21
+
22
+ Uses your existing AWS credentials (SSO, profiles, env vars)
23
+
24
+ Validates SSH key path and permissions (Unix)
25
+
26
+ Requirements
27
+ AWS account permissions to use SSM Session Manager
28
+
29
+ Locally installed:
30
+
31
+ AWS CLI v2
32
+
33
+ SSM Session Manager plugin
34
+
35
+ OpenSSH client (ssh)
36
+
37
+ Python 3.8+
38
+
39
+ boto3 (installed automatically if using PyPI package)
40
+
41
+ On Linux/macOS, ensure a terminal emulator exists (e.g., gnome-terminal, xterm, or Terminal.app on macOS). On Windows, PowerShell or Windows Terminal recommended.
42
+
43
+ Install
44
+ From source:
45
+
46
+ Clone this repo and run the script with Python 3.
47
+
48
+ From PyPI (if published):
49
+
50
+ pip install ssm-connect
51
+
52
+ ssm-connect
53
+
54
+ Usage
55
+ Run the tool
56
+
57
+ Optionally enter keywords to filter instances (e.g., “prod web”)
58
+
59
+ Select an instance
60
+
61
+ Choose connection type:
62
+
63
+ SSM (interactive shell)
64
+
65
+ SSH over SSM (enter SSH key path and user)
66
+
67
+ For SSH, choose whether to enable strict host key checking
68
+
69
+ Each session opens in a new terminal; you can open more without restarting the tool
70
+
71
+ Notes
72
+ SSH over SSM uses AWS-StartSSHSession and does not require port 22 open in security groups.
73
+
74
+ Strict host key checking is disabled by default for convenience; enable it for production/security-sensitive use.
75
+
76
+ The tool does not print or store credentials; it inherits your AWS session from the environment/AWS CLI.
77
+
78
+ Troubleshooting
79
+ If “aws” or “ssh” not found: ensure AWS CLI v2 and OpenSSH are on PATH.
80
+
81
+ If SSO token expired: run aws sso login or refresh your Granted/SSO session.
82
+
83
+ If SSH key error: ensure the private key exists locally and has correct permissions (chmod 600 on Unix). Avoid cloud-only paths (e.g., OneDrive placeholders).
84
+
85
+ License
86
+ Apache License 2.0. See LICENSE for details.
87
+
88
+ Contributing
89
+ Issues and PRs are welcome. Please keep changes focused and add brief notes to the README when behavior changes.
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ssm-connect"
7
+ version = "1.0.0"
8
+ description = "Interactive CLI to connect to AWS EC2 via SSM or SSH-over-SSM, with keyword search and multi-session terminal launch."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [
13
+ { name = "Your Name", email = "you@example.com" }
14
+ ]
15
+ keywords = ["aws", "ec2", "ssm", "ssh", "cli", "session-manager"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Intended Audience :: System Administrators",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ "Programming Language :: Python :: 3.8",
25
+ "Programming Language :: Python :: 3.9",
26
+ "Programming Language :: Python :: 3.10",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Topic :: System :: Systems Administration",
30
+ "Topic :: Utilities",
31
+ ]
32
+
33
+ dependencies = [
34
+ "boto3>=1.26.0",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/yourusername/ssm-connect"
39
+ Issues = "https://github.com/yourusername/ssm-connect/issues"
40
+ Source = "https://github.com/yourusername/ssm-connect"
41
+
42
+ [project.scripts]
43
+ ssm-connect = "ssm_connect.main:main"
44
+
45
+ [tool.setuptools.packages.find]
46
+ where = ["src"]
47
+
48
+ [tool.setuptools.package-dir]
49
+ "" = "src"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ from setuptools import setup
2
+ setup()
@@ -0,0 +1 @@
1
+ version = "1.0.0"
@@ -0,0 +1,345 @@
1
+ ## Copyright 2025 Siby Jose
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # !/usr/bin/env python3
16
+ import os
17
+ import sys
18
+ import subprocess
19
+ import stat
20
+ from pathlib import Path
21
+ from typing import List, Dict, Optional, Tuple
22
+ from enum import Enum
23
+ import shutil
24
+ import platform
25
+ import shlex
26
+ import boto3
27
+ from botocore.config import Config
28
+ from botocore.exceptions import BotoCoreError, ClientError, NoCredentialsError
29
+
30
+ Instance = Dict[str, str]
31
+
32
+ class ConnectionType(Enum):
33
+ SSM = "ssm"
34
+ SSH = "ssh"
35
+
36
+ def make_boto3_session() -> boto3.Session:
37
+ os.environ.setdefault("AWS_SDK_LOAD_CONFIG", "1")
38
+ return boto3.Session()
39
+
40
+ def get_session_credentials(session: boto3.Session) -> Dict[str, str]:
41
+ try:
42
+ credentials = session.get_credentials()
43
+ if not credentials:
44
+ return {}
45
+ frozen = credentials.get_frozen_credentials()
46
+ env_creds = {
47
+ "AWS_ACCESS_KEY_ID": frozen.access_key,
48
+ "AWS_SECRET_ACCESS_KEY": frozen.secret_key,
49
+ }
50
+ if frozen.token:
51
+ env_creds["AWS_SESSION_TOKEN"] = frozen.token
52
+ return env_creds
53
+ except NoCredentialsError:
54
+ print("Warning: Could not resolve AWS credentials from the session.", file=sys.stderr)
55
+ return {}
56
+
57
+ def _get_instance_name(tags: Optional[List[Dict[str, str]]]) -> str:
58
+ if not tags:
59
+ return "Unnamed"
60
+ for tag in tags:
61
+ if tag.get("Key") == "Name":
62
+ return tag.get("Value", "Unnamed")
63
+ return "Unnamed"
64
+
65
+ def validate_key_permissions(key_path: Path) -> bool:
66
+ if os.name == 'nt':
67
+ return True
68
+ try:
69
+ mode = key_path.stat().st_mode
70
+ if mode & (stat.S_IRWXG | stat.S_IRWXO):
71
+ print(f"\nWarning: Private key '{key_path}' has overly permissive access.", file=sys.stderr)
72
+ print(f" To fix, run: chmod 600 {key_path}", file=sys.stderr)
73
+ return False
74
+ return True
75
+ except Exception as e:
76
+ print(f"Warning: Could not check key permissions: {e}", file=sys.stderr)
77
+ return True
78
+
79
+ def list_running_instances(session: boto3.Session) -> List[Instance]:
80
+ ec2 = session.client("ec2", config=Config(retries={"max_attempts": 5}))
81
+ paginator = ec2.get_paginator("describe_instances")
82
+ filters = [{"Name": "instance-state-name", "Values": ["running"]}]
83
+ instances = []
84
+ for page in paginator.paginate(Filters=filters):
85
+ for reservation in page.get("Reservations", []):
86
+ for inst in reservation.get("Instances", []):
87
+ tags = inst.get("Tags") or []
88
+ flat_tags = {tag['Key'].lower(): (tag.get('Value') or '').lower() for tag in tags if 'Key' in tag}
89
+ all_tag_values = ' '.join(flat_tags.values())
90
+ instances.append({
91
+ "InstanceId": inst.get("InstanceId"),
92
+ "Name": _get_instance_name(tags),
93
+ "AllTagsBlob": all_tag_values
94
+ })
95
+ return instances
96
+
97
+ def prompt_for_keywords() -> Optional[List[str]]:
98
+ raw = input("\n(Optional) Enter keywords to filter instances (or press ENTER to list all): ").strip()
99
+ if not raw:
100
+ return None
101
+ return [s.lower() for s in raw.replace(',', ' ').split() if s.strip()]
102
+
103
+ def filter_instances_by_keywords(instances: List[Instance], keywords: Optional[List[str]]) -> List[Instance]:
104
+ if not keywords:
105
+ return instances
106
+ filtered = []
107
+ for inst in instances:
108
+ search_blob = (
109
+ inst.get("Name", "").lower() + " " +
110
+ inst.get("InstanceId", "").lower() + " " +
111
+ inst.get("AllTagsBlob", "")
112
+ )
113
+ if all(kw in search_blob for kw in keywords):
114
+ filtered.append(inst)
115
+ return filtered
116
+
117
+ def choose_instance(instances: List[Instance]) -> Optional[str]:
118
+ if not instances:
119
+ return None
120
+ print("\nSelect an EC2 Instance:")
121
+ for idx, inst in enumerate(instances, start=1):
122
+ print(f"[{idx}] {inst['Name']} ({inst['InstanceId']})")
123
+ print("[0] Exit / Refine Search")
124
+ try:
125
+ raw_choice = input("\nEnter the number of the instance to connect to: ").strip()
126
+ if raw_choice == "0":
127
+ return "RETRY"
128
+ choice_idx = int(raw_choice) - 1
129
+ if 0 <= choice_idx < len(instances):
130
+ return instances[choice_idx]["InstanceId"]
131
+ except (ValueError, IndexError):
132
+ return None
133
+ return None
134
+
135
+ def choose_connection_type() -> Optional[ConnectionType]:
136
+ print("\nSelect connection type:")
137
+ print("[1] SSM Session (interactive shell)")
138
+ print("[2] SSH over SSM (requires private key)")
139
+ try:
140
+ choice = input("\nEnter your choice (1 or 2): ").strip()
141
+ if choice == "1":
142
+ return ConnectionType.SSM
143
+ elif choice == "2":
144
+ return ConnectionType.SSH
145
+ else:
146
+ return None
147
+ except (ValueError, KeyboardInterrupt):
148
+ return None
149
+
150
+ def prompt_for_ssh_details() -> Optional[Tuple[str, Path]]:
151
+ key_path_str = input("\nEnter the path to your private key file: ").strip()
152
+ if not key_path_str:
153
+ print("Error: Private key path cannot be empty.", file=sys.stderr)
154
+ return None
155
+ key_path = Path(key_path_str.strip('"\'')).expanduser()
156
+ if not key_path.is_file():
157
+ print(f"Error: Private key file not found or is not a file at '{key_path}'", file=sys.stderr)
158
+ return None
159
+ if not validate_key_permissions(key_path):
160
+ response = input("Continue anyway? (y/N): ").strip().lower()
161
+ if response != 'y':
162
+ return None
163
+ username = input("Enter SSH username (e.g., ec2-user, ubuntu): ").strip()
164
+ if not username:
165
+ print("Error: Username cannot be empty.", file=sys.stderr)
166
+ return None
167
+ return username, key_path
168
+
169
+ def get_host_key_checking_choice() -> bool:
170
+ choice = input(
171
+ "Enable strict SSH host key checking? [y/N]: "
172
+ ).strip().lower()
173
+ return choice == "y"
174
+
175
+ def _prepare_subprocess_env(session: boto3.Session) -> Dict[str, str]:
176
+ env = os.environ.copy()
177
+ creds = get_session_credentials(session)
178
+ env.update(creds)
179
+ if session.region_name:
180
+ env["AWS_REGION"] = session.region_name
181
+ env["AWS_DEFAULT_REGION"] = session.region_name
182
+ return env
183
+
184
+ def open_in_new_terminal(command: list, env: dict):
185
+ if sys.platform.startswith("linux"):
186
+ if shutil.which("gnome-terminal"):
187
+ safe_command = " ".join(shlex.quote(arg) for arg in command) + "; exec bash"
188
+ subprocess.Popen(["gnome-terminal", "--", "bash", "-c", safe_command], env=env)
189
+ elif shutil.which("konsole"):
190
+ subprocess.Popen(["konsole", "-e"] + command, env=env)
191
+ elif shutil.which("xterm"):
192
+ subprocess.Popen(["xterm", "-e"] + command, env=env)
193
+ elif shutil.which("x-terminal-emulator"):
194
+ subprocess.Popen(["x-terminal-emulator", "-e"] + command, env=env)
195
+ else:
196
+ print("No supported terminal emulator found, running in current window.", file=sys.stderr)
197
+ subprocess.Popen(command, env=env)
198
+
199
+ elif sys.platform == "darwin":
200
+ safe_command = " ".join(shlex.quote(arg) for arg in command)
201
+ applescript_safe_command = safe_command.replace('"', '\\"')
202
+ subprocess.Popen([
203
+ "osascript",
204
+ "-e",
205
+ f'tell application "Terminal" to do script "{applescript_safe_command}"'
206
+ ], env=env)
207
+
208
+ elif os.name == "nt":
209
+ safe_command = subprocess.list2cmdline(command)
210
+
211
+ if shutil.which("wt"):
212
+ subprocess.Popen(["wt", "new-tab", "cmd", "/k", safe_command], env=env)
213
+ elif shutil.which("powershell"):
214
+ subprocess.Popen([
215
+ "powershell",
216
+ "-Command",
217
+ f"Start-Process powershell -ArgumentList '-NoExit', '-Command', {repr(safe_command)}"
218
+ ], env=env)
219
+ else:
220
+ # Fallback to cmd - use start with quoted command
221
+ subprocess.Popen(["cmd", "/c", "start", "cmd", "/k", safe_command], env=env)
222
+
223
+ else:
224
+ print("Unknown OS: running the command in the current terminal.")
225
+ subprocess.Popen(command, env=env)
226
+
227
+ def start_ssm_session(instance_id: str, session: boto3.Session) -> int:
228
+ env = _prepare_subprocess_env(session)
229
+ cmd = ["aws", "ssm", "start-session", "--target", instance_id]
230
+ try:
231
+ print(f"\nOpening SSM session to {instance_id} in a new terminal window.")
232
+ print("You can now open additional sessions by making another selection.\n")
233
+ open_in_new_terminal(cmd, env)
234
+ return 0
235
+ except Exception as e:
236
+ print(f"Error opening terminal: {e}", file=sys.stderr)
237
+ print("Falling back to current terminal session.", file=sys.stderr)
238
+ try:
239
+ result = subprocess.run(cmd, env=env)
240
+ return result.returncode
241
+ except FileNotFoundError:
242
+ print("Error: 'aws' command not found. Please ensure the AWS CLI is installed.", file=sys.stderr)
243
+ return 1
244
+ except KeyboardInterrupt:
245
+ print("\nSSM session terminated.")
246
+ return 0
247
+
248
+ def start_ssh_session(instance_id: str, username: str, key_path: Path, session: boto3.Session) -> int:
249
+ env = _prepare_subprocess_env(session)
250
+ proxy_command = (
251
+ f"aws ssm start-session --target {instance_id} "
252
+ f"--document-name AWS-StartSSHSession --parameters portNumber=%p"
253
+ )
254
+ strict_host_check = get_host_key_checking_choice()
255
+ ssh_cmd = [
256
+ "ssh", "-i", str(key_path.resolve()),
257
+ "-o", f"ProxyCommand={proxy_command}",
258
+ "-o", "IdentitiesOnly=yes"
259
+ ]
260
+ if not strict_host_check:
261
+ ssh_cmd += [
262
+ "-o", "StrictHostKeyChecking=no",
263
+ "-o", "UserKnownHostsFile=/dev/null"
264
+ ]
265
+ ssh_cmd.append(f"{username}@{instance_id}")
266
+ try:
267
+ print(f"\nOpening SSH over SSM session to {instance_id} as '{username}' in a new terminal window.")
268
+ print("You can now open additional sessions by making another selection.\n")
269
+ open_in_new_terminal(ssh_cmd, env)
270
+ return 0
271
+ except Exception as e:
272
+ print(f"Error opening terminal: {e}", file=sys.stderr)
273
+ print("Falling back to current terminal session.", file=sys.stderr)
274
+ try:
275
+ result = subprocess.run(ssh_cmd, env=env)
276
+ return result.returncode
277
+ except FileNotFoundError:
278
+ print("Error: 'ssh' or 'aws' command not found. Ensure both are installed.", file=sys.stderr)
279
+ return 1
280
+ except KeyboardInterrupt:
281
+ print("\nSSH session terminated.")
282
+ return 0
283
+
284
+ def ask_continue_or_exit():
285
+ choice = input("\nWould you like to open another session? [Y/n]: ").strip().lower()
286
+ return choice != 'n' and choice != 'no'
287
+
288
+ def main():
289
+ try:
290
+ session = make_boto3_session()
291
+ all_instances = list_running_instances(session)
292
+ except (BotoCoreError, ClientError) as e:
293
+ print(f"AWS API Error: Failed to list instances: {e}", file=sys.stderr)
294
+ print("\nTip: Ensure your AWS credentials are configured correctly.", file=sys.stderr)
295
+ sys.exit(1)
296
+
297
+ if not all_instances:
298
+ print(f"No running instances found in region '{session.region_name}'.")
299
+ sys.exit(0)
300
+
301
+ print(f"Found {len(all_instances)} running instances in region '{session.region_name}'.")
302
+
303
+ while True:
304
+ instance_id = None
305
+
306
+ while not instance_id:
307
+ keywords = prompt_for_keywords()
308
+ filtered_instances = filter_instances_by_keywords(all_instances, keywords)
309
+
310
+ if not filtered_instances:
311
+ print("No instances found matching your keywords. Please try again.")
312
+ continue
313
+
314
+ selection = choose_instance(filtered_instances)
315
+ if selection is None:
316
+ print("Invalid selection. Please try again.", file=sys.stderr)
317
+ continue
318
+ elif selection == "RETRY":
319
+ continue
320
+ else:
321
+ instance_id = selection
322
+
323
+ connection_type = choose_connection_type()
324
+ if not connection_type:
325
+ print("Invalid connection type. Exiting.", file=sys.stderr)
326
+ sys.exit(1)
327
+
328
+ if connection_type == ConnectionType.SSM:
329
+ start_ssm_session(instance_id, session)
330
+ elif connection_type == ConnectionType.SSH:
331
+ ssh_details = prompt_for_ssh_details()
332
+ if ssh_details:
333
+ username, key_path = ssh_details
334
+ start_ssh_session(instance_id, username, key_path, session)
335
+ else:
336
+ print("Failed to get SSH details.")
337
+ continue
338
+
339
+ if not ask_continue_or_exit():
340
+ break
341
+
342
+ print("Goodbye!")
343
+
344
+ if __name__ == "__main__":
345
+ main()
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.4
2
+ Name: ssm-connect
3
+ Version: 1.0.0
4
+ Summary: Interactive CLI to connect to AWS EC2 via SSM or SSH-over-SSM, with keyword search and multi-session terminal launch.
5
+ Author-email: Your Name <you@example.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/yourusername/ssm-connect
8
+ Project-URL: Issues, https://github.com/yourusername/ssm-connect/issues
9
+ Project-URL: Source, https://github.com/yourusername/ssm-connect
10
+ Keywords: aws,ec2,ssm,ssh,cli,session-manager
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Topic :: System :: Systems Administration
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: boto3>=1.26.0
29
+ Dynamic: license-file
30
+
31
+ Interactive CLI to connect to AWS EC2 instances via:
32
+
33
+ SSM Session Manager (shell)
34
+
35
+ SSH over SSM (with your SSH key)
36
+
37
+ Multiple sessions in parallel (opens each in a new terminal)
38
+
39
+ Keyword search across Name/ID/all tag values
40
+
41
+ Simple, cross-platform, and secure by default.
42
+
43
+ Features
44
+ Search instances by keywords (matches Name, InstanceId, and all tag values)
45
+
46
+ Choose SSM or SSH-over-SSM per connection
47
+
48
+ Optional strict SSH host key checking (security toggle)
49
+
50
+ Opens each session in a new terminal window (Linux, macOS, Windows)
51
+
52
+ Uses your existing AWS credentials (SSO, profiles, env vars)
53
+
54
+ Validates SSH key path and permissions (Unix)
55
+
56
+ Requirements
57
+ AWS account permissions to use SSM Session Manager
58
+
59
+ Locally installed:
60
+
61
+ AWS CLI v2
62
+
63
+ SSM Session Manager plugin
64
+
65
+ OpenSSH client (ssh)
66
+
67
+ Python 3.8+
68
+
69
+ boto3 (installed automatically if using PyPI package)
70
+
71
+ On Linux/macOS, ensure a terminal emulator exists (e.g., gnome-terminal, xterm, or Terminal.app on macOS). On Windows, PowerShell or Windows Terminal recommended.
72
+
73
+ Install
74
+ From source:
75
+
76
+ Clone this repo and run the script with Python 3.
77
+
78
+ From PyPI (if published):
79
+
80
+ pip install ssm-connect
81
+
82
+ ssm-connect
83
+
84
+ Usage
85
+ Run the tool
86
+
87
+ Optionally enter keywords to filter instances (e.g., “prod web”)
88
+
89
+ Select an instance
90
+
91
+ Choose connection type:
92
+
93
+ SSM (interactive shell)
94
+
95
+ SSH over SSM (enter SSH key path and user)
96
+
97
+ For SSH, choose whether to enable strict host key checking
98
+
99
+ Each session opens in a new terminal; you can open more without restarting the tool
100
+
101
+ Notes
102
+ SSH over SSM uses AWS-StartSSHSession and does not require port 22 open in security groups.
103
+
104
+ Strict host key checking is disabled by default for convenience; enable it for production/security-sensitive use.
105
+
106
+ The tool does not print or store credentials; it inherits your AWS session from the environment/AWS CLI.
107
+
108
+ Troubleshooting
109
+ If “aws” or “ssh” not found: ensure AWS CLI v2 and OpenSSH are on PATH.
110
+
111
+ If SSO token expired: run aws sso login or refresh your Granted/SSO session.
112
+
113
+ If SSH key error: ensure the private key exists locally and has correct permissions (chmod 600 on Unix). Avoid cloud-only paths (e.g., OneDrive placeholders).
114
+
115
+ License
116
+ Apache License 2.0. See LICENSE for details.
117
+
118
+ Contributing
119
+ Issues and PRs are welcome. Please keep changes focused and add brief notes to the README when behavior changes.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ src/ssm_connect/init.py
6
+ src/ssm_connect/main.py
7
+ src/ssm_connect.egg-info/PKG-INFO
8
+ src/ssm_connect.egg-info/SOURCES.txt
9
+ src/ssm_connect.egg-info/dependency_links.txt
10
+ src/ssm_connect.egg-info/entry_points.txt
11
+ src/ssm_connect.egg-info/requires.txt
12
+ src/ssm_connect.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ssm-connect = ssm_connect.main:main
@@ -0,0 +1 @@
1
+ boto3>=1.26.0
@@ -0,0 +1 @@
1
+ ssm_connect