--- /dev/null
+__pycache__/
+build/
+dist/
+*.egg-info/
--- /dev/null
+# Released under MIT License
+
+Copyright (c) 2025 Andreas Glashauser.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--- /dev/null
+# knockssh
+
+**knockssh** is a simple wrapper around [`ssh`](https://man.openbsd.org/ssh.1) and [`knock`](https://github.com/jvinet/knock), aimed at making the port-knocking workflow more convenient.
+It helps ensure your ports remain secure by reliably executing knock sequences before and after SSH sessions, so you'll never leave ports exposed by mistake.
+
+## Installation
+### Manual Installation from Source (Recommended)
+
+The recommended approach is to install **knockssh** directly from source:
+
+```bash
+git clone https://git.andreasglashauser.com/git/knockssh.git
+cd knockssh
+pip install .
+```
+### Install from PyPI
+**knockssh** is published on [PyPI](https://pypi.org/project/knockssh/).
+
+To install the latest release:
+```bash
+pip install knockssh
+```
+After installation, you can run:
+
+```bash
+knockssh --help
+```
+
+## Usage
+Once installed, you can use `knockssh` to manage your SSH connections with integrated port-knocking.
+It uses a configuration file (default: `~/.knockssh.conf`) to store connection profiles, but you can override everything via command-line options.
+
+### Command-Line Options
+```
+-s, --save Save or update the specified profile in the config file and exit
+-p, --profile NAME Profile name to use or update (default: 'default')
+-H, --host HOST Override or set the host
+-U, --user USER Override or set the user name (default: 'user')
+-P, --port PORT Override or set the SSH port (default: 22)
+-O, --open-ports PORTS Comma-separated ports to knock for opening
+-C, --close-ports PORTS Comma-separated ports to knock for closing
+-f, --config-file FILE Path to alternative config file (default: ~/.knockssh.conf)
+-v, --verbose Increase verbosity (use multiple times for more detail)
+```
+
+## Examples
+### Basic SSH Connection with Port Knocking
+
+If you have a profile already defined:
+
+```bash
+knockssh
+```
+
+This will:
+- Load the default profile from the config file
+- Execute the "open" knock sequence
+- Initiate the SSH connection
+- Execute the "close" knock sequence after the SSH session ends
+
+### Using a Specific Profile
+```bash
+knockssh -p another_profile
+```
+
+Loads and uses the `another_profile` entry from the config.
+
+### Direct Connection Parameters (No Profile)
+```bash
+knockssh -p myserver -H 1.2.3.4 -U user -O 7000,8000 -C 8000,7000
+```
+
+This will:
+- Use `myserver` as the temporary profile name
+- Connect to `1.2.3.4` with user `user`
+- Knock ports 7000, 8000 to open
+- SSH to the host
+- Knock ports 8000, 7000 to close
+
+### Saving a New Profile
+```bash
+knockssh --save -p new_profile --host myserver.com --ssh-port 2222 --user user --open-ports 1234,2345 --close-ports 2345,1234
+```
+
+This saves the given settings into the config file under `new_profile`. No SSH connection will be started.
+
+### Updating an Existing Profile
+```bash
+knockssh --save -p another_server -H changed-host.com
+```
+
+This updates just the host of the `another_server` profile.
+
+If you encounter any issues, have questions, or require further clarification, feel free to contact me. Happy knocking!
--- /dev/null
+import subprocess
+
+class CommandExecutor:
+ def __init__(self, logger):
+ self.logger = logger
+
+ def run(self, command, success_message, check=True):
+ self.logger.debug(f"Running command: {command}")
+ result = subprocess.run(command, check=check)
+ if check:
+ self.logger.info(success_message)
+ return result
--- /dev/null
+from configparser import ConfigParser
+from typing import Dict, Union
+import os
+
+class ConfigLoader:
+ def __init__(self, logger, config_file_path, profile, host, port, user, open_ports, close_ports):
+ self.config_file_path = os.path.expanduser(config_file_path)
+ self.profile = profile
+ self.logger = logger
+ self.host = host
+ self.port = port
+ self.user = user
+ self.open_ports = open_ports
+ self.close_ports = close_ports
+
+ def load(self) -> Dict[str, Union[str, int]]:
+ config = ConfigParser()
+ config.read(self.config_file_path)
+
+ if self.profile not in config:
+ raise ValueError(f"Profile '{self.profile}' not found in config file.")
+
+ self.logger.debug(f"Loaded profile '{self.profile}' from config file.")
+
+ return {
+ "host": self.host or config[self.profile]["host"],
+ "port": self.port or config[self.profile]["ssh_port"],
+ "user": self.user or config[self.profile]["user"],
+ "open_ports": self.open_ports or config[self.profile]["open_ports"],
+ "close_ports": self.close_ports or config[self.profile]["close_ports"]
+ }
--- /dev/null
+from configparser import ConfigParser
+import os
+
+class ConfigSaver:
+ def __init__(self, logger, config_file_path, profile, host, port, user, open_ports, close_ports):
+ self.config_file_path = os.path.expanduser(config_file_path)
+ self.profile = profile
+ self.host = host
+ self.port = port
+ self.user = user
+ self.open_ports = open_ports
+ self.close_ports = close_ports
+ self.logger = logger
+
+ def save(self):
+ config = ConfigParser()
+ config.read(self.config_file_path)
+ if self.profile in config:
+ self.logger.debug(f"Found existing configuration")
+ self._update_existing_profile(config)
+ else:
+ self.logger.debug(f"Create new profile")
+ self._create_new_profile(config)
+
+ with open(self.config_file_path, 'w') as f:
+ config.write(f)
+ self.logger.debug(f"Configuration saved to {self.config_file_path}")
+
+ def _update_existing_profile(self, config):
+ profile = config[self.profile]
+ profile["host"] = self.host or profile.get("host")
+ profile["ssh_port"] = self.port or profile.get("ssh_port")
+ profile["user"] = self.user or profile.get("user")
+ profile["open_ports"] = self.open_ports or profile.get("open_ports")
+ profile["close_ports"] = self.close_ports or profile.get("close_ports")
+
+ def _create_new_profile(self, config):
+ config[self.profile] = {
+ "host": str(self.host),
+ "ssh_port": self.port or str(22),
+ "user": self.user or "user",
+ "open_ports": str(self.open_ports),
+ "close_ports": str(self.close_ports)
+ }
+ self.logger.debug(f"Created new profile '{self.profile}'")
--- /dev/null
+import logging
+
+class Logger:
+ def __init__(self, verbosity):
+ logging_level = self._map_verbosity(verbosity)
+ logging.basicConfig(
+ level=logging_level,
+ format="%(asctime)s [%(levelname)s] %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ )
+
+ def _map_verbosity(self, verbosity):
+ if verbosity >= 3:
+ return logging.DEBUG
+ elif verbosity == 2:
+ return logging.INFO
+ elif verbosity == 1:
+ return logging.WARNING
+ else:
+ return logging.ERROR
+
+ def debug(self, msg):
+ logging.debug(msg)
+
+ def info(self, msg):
+ logging.info(msg)
+
+ def warning(self, msg):
+ logging.warning(msg)
+
+ def error(self, msg):
+ logging.error(msg)
+
+_logger_instance = None
+
+def init_logger(verbosity) -> Logger:
+ global _logger_instance
+ if _logger_instance is None:
+ _logger_instance = Logger(verbosity)
+ _logger_instance.info("Logger initialized")
+ return _logger_instance
+
+def get_logger() -> Logger:
+ if _logger_instance is None:
+ raise Exception("Logger not initialized yet.")
+ return _logger_instance
--- /dev/null
+from argparse import ArgumentParser, RawDescriptionHelpFormatter, SUPPRESS
+from .config_loader import ConfigLoader
+from .config_saver import ConfigSaver
+from .logger_singleton import init_logger
+from .command_executor import CommandExecutor
+import shutil
+import sys
+
+def create_parser() -> ArgumentParser:
+ example_usage = """
+Example Usage:
+
+\t$ knockssh
+\t$ knockssh -p another_profile
+\t$ knockssh -p myserver -H 1.2.3.4 -U user -O 7000,8000 -C 8000,7000
+\t$ knockssh --save -p new_profile --host myserver.com --port 2222 --user user --open-ports 1234,2345 --close-ports 2345,1234
+\t$ knockssh --save -p another_server -H changed-hosd.org
+ """
+
+ parser = ArgumentParser(
+ prog="knockssh"
+ , description = "knockssh is a wrapper around knock and"
+ + " ssh, which enables you to use this combination more easily."
+ , epilog = example_usage
+ , formatter_class = RawDescriptionHelpFormatter
+ )
+
+ parser.add_argument("-s", "--save", action="store_true", help="Save/update the specified profile in the config file, then exit")
+ parser.add_argument("-p", "--profile", default="default", help="Profile name to use or update (default: 'default')")
+ parser.add_argument("-H", "--host", help="Override or set the host")
+ parser.add_argument("-U", "--user", help="Override or set the user name (default: 'user')")
+ parser.add_argument("-P", "--port", help="Override or set the SSH port (default: 22)")
+ parser.add_argument("-O", "--open-ports", help="Comma-separated ports to knock for opening")
+ parser.add_argument("-C", "--close-ports", help="Comma-separated ports to knock for closing")
+ parser.add_argument("-f", "--config-file", default="~/.knockssh.conf", help="Specify an alternative config file (default: ~/.knockssh.conf)")
+ parser.add_argument("-v", "--verbose", default=0, action="count")
+ parser.add_argument("--generate-manpage", action="store_true", help=SUPPRESS)
+
+ return parser
+
+def execute_knock(config, executor, ports_key, success_msg):
+ ports = config[ports_key].split(',')
+ command = ["knock", "-v", config["host"], *ports]
+ executor.run(command, success_msg)
+
+def execute_ssh(config, executor):
+ command = ["ssh", "-p", str(config["port"]), f"{config['user']}@{config['host']}"]
+ result = executor.run(command, "SSH connection successful.", check=False)
+ if result.returncode != 0:
+ executor.logger.info(f"SSH session ended with exit code {result.returncode}.")
+
+def execute_knock_open(config, executor):
+ execute_knock(config, executor, "open_ports", "Ports opened successfully.")
+
+def execute_knock_close(config, executor):
+ execute_knock(config, executor, "close_ports", "Ports closed successfully.")
+
+def main():
+ if not all(shutil.which(cmd) for cmd in ["knock", "ssh"]):
+ sys.exit("This program requires both 'knock'and 'ssh' packages to be installed")
+
+ parser = create_parser()
+ args = parser.parse_args()
+
+ logger = init_logger(args.verbose)
+ logger.debug(f"Arguments parsed: {args}")
+
+ logger.debug(f"Config file set to: {args.config_file}")
+
+ arg_values = {
+ "config_file_path": args.config_file,
+ "profile": args.profile,
+ "host": args.host,
+ "port": args.port,
+ "user": args.user,
+ "open_ports": args.open_ports,
+ "close_ports": args.close_ports,
+ }
+
+ if args.save:
+ logger.info(f"Saving profile '{args.profile}'...")
+ config_saver = ConfigSaver(logger, **arg_values
+ )
+ try:
+ config_saver.save()
+ logger.info("Configuration saved successfully.")
+ except Exception as e:
+ logger.error(f"Failed to save configuration: {e}")
+ return
+
+ logger.info(f"Loading configuration for profile '{args.profile}'...")
+ config_loader = ConfigLoader(logger, **arg_values)
+ try:
+ config = config_loader.load()
+ logger.info(f"Configuration loaded: {config}")
+ except ValueError as e:
+ logger.error(f"Configuration load failed: {e}")
+ return
+
+ executor = CommandExecutor(logger)
+ logger.debug("Executing knock open...")
+ execute_knock_open(config, executor)
+
+ logger.debug("Executing SSH connection...")
+ execute_ssh(config, executor)
+
+ logger.debug("Executing knock close...")
+ execute_knock_close(config, executor)
+
+if __name__ == "__main__":
+ main()
--- /dev/null
+[build-system]
+requires = ["setuptools>=61.0", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "knockssh"
+version = "0.1.0"
+description = "knockssh automates knock-and-ssh for a more convenient workflow"
+authors = [
+ { name = "Andreas Glashauser", email = "ag@andreasglashauser.com" },
+]
+readme = "README.md"
+license = "MIT"
+license-files = ["LICENSE"]
+requires-python = ">=3.6"
+classifiers = [
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "Programming Language :: Python :: 3",
+]
+
+dependencies = [
+]
+
+[project.urls]
+"Source" = "https://git.andreasglashauser.com/?p=knockssh.git"
+
+[project.scripts]
+knockssh = "knockssh.main:main"