A Python library for persistent SSH agent management with automatic key handling, focusing on Windows compatibility and seamless Git integration.
Project description
persistent-ssh-agent
๐ A modern Python library for persistent SSH agent management across sessions.
๐ Table of Contents
โจ Features
- ๐ Persistent SSH agent management across sessions
- ๐ Automatic SSH key loading and caching
- ๐ช Windows-optimized implementation
- ๐ Seamless Git integration
- ๐ Cross-platform compatibility (Windows, Linux, macOS)
- ๐ฆ No external dependencies beyond standard SSH tools
- ๐ Secure key management and session control with AES-256 encryption
- โก Asynchronous operation support
- ๐งช Complete unit test coverage with performance benchmarks
- ๐ Comprehensive type hints support
- ๐ Support for multiple SSH key types (Ed25519, ECDSA, RSA)
- ๐ IPv6 support
- ๐ Multi-language documentation support
- ๐ Enhanced SSH configuration validation
- ๐ ๏ธ Modern development toolchain (Poetry, Commitizen, Black)
- ๐ Git credential helper integration for seamless Git operations
- ๐ป Command-line interface with comprehensive configuration options
๐ Installation
pip install persistent-ssh-agent
๐ Requirements
- Python 3.8-3.13
- OpenSSH (ssh-agent, ssh-add) installed and available in PATH
- Git (optional, for Git operations)
๐ Usage
Basic Usage
from persistent_ssh_agent import PersistentSSHAgent
# Create an instance with custom expiration time (default is 24 hours)
ssh_agent = PersistentSSHAgent(expiration_time=86400)
# Set up SSH for a specific host
if ssh_agent.setup_ssh('github.com'):
print("โ
SSH authentication ready!")
Advanced Configuration
from persistent_ssh_agent import PersistentSSHAgent
from persistent_ssh_agent.config import SSHConfig
# Create custom SSH configuration
config = SSHConfig(
identity_file='~/.ssh/github_key', # Optional specific identity file
identity_passphrase='your-passphrase', # Optional passphrase
ssh_options={ # Optional SSH options
'StrictHostKeyChecking': 'yes',
'PasswordAuthentication': 'no',
'PubkeyAuthentication': 'yes'
}
)
# Initialize with custom config and agent reuse settings
ssh_agent = PersistentSSHAgent(
config=config,
expiration_time=86400, # Optional: Set agent expiration time (default 24 hours)
reuse_agent=True # Optional: Control agent reuse behavior (default True)
)
# Set up SSH authentication
if ssh_agent.setup_ssh('github.com'):
# Get Git SSH command for the host
ssh_command = ssh_agent.get_git_ssh_command('github.com')
if ssh_command:
print("โ
Git SSH command ready!")
Agent Reuse Behavior
The reuse_agent parameter controls how the SSH agent handles existing sessions:
-
When
reuse_agent=True(default):- Attempts to reuse an existing SSH agent if available
- Reduces the number of agent startups and key additions
- Improves performance by avoiding unnecessary agent operations
-
When
reuse_agent=False:- Always starts a new SSH agent session
- Useful when you need a fresh agent state
- May be preferred in certain security-sensitive environments
Example with agent reuse disabled:
# Always start a new agent session
ssh_agent = PersistentSSHAgent(reuse_agent=False)
Multiple Host Configuration
from persistent_ssh_agent import PersistentSSHAgent
from persistent_ssh_agent.config import SSHConfig
# Create configuration with common options
config = SSHConfig(
ssh_options={
'BatchMode': 'yes',
'StrictHostKeyChecking': 'yes',
'ServerAliveInterval': '60'
}
)
# Initialize agent
agent = PersistentSSHAgent(config=config)
# Set up SSH for multiple hosts
hosts = ['github.com', 'gitlab.com', 'bitbucket.org']
for host in hosts:
if agent.setup_ssh(host):
print(f"โ
SSH configured for {host}")
else:
print(f"โ Failed to configure SSH for {host}")
Global SSH Configuration
from persistent_ssh_agent import PersistentSSHAgent
from persistent_ssh_agent.config import SSHConfig
# Create configuration with global options
config = SSHConfig(
# Set identity file (optional)
identity_file='~/.ssh/id_ed25519',
# Set global SSH options
ssh_options={
'StrictHostKeyChecking': 'yes',
'PasswordAuthentication': 'no',
'PubkeyAuthentication': 'yes',
'BatchMode': 'yes',
'ConnectTimeout': '30'
}
)
# Initialize agent with global configuration
agent = PersistentSSHAgent(config=config)
Asynchronous Support
import asyncio
from persistent_ssh_agent import PersistentSSHAgent
async def setup_multiple_hosts(hosts: list[str]) -> dict[str, bool]:
"""Set up SSH for multiple hosts concurrently."""
ssh_agent = PersistentSSHAgent()
results = {}
async def setup_host(host: str):
results[host] = await ssh_agent.async_setup_ssh(host)
await asyncio.gather(*[setup_host(host) for host in hosts])
return results
# Usage example
async def main():
hosts = ['github.com', 'gitlab.com', 'bitbucket.org']
results = await setup_multiple_hosts(hosts)
for host, success in results.items():
print(f"{host}: {'โ
' if success else 'โ'}")
asyncio.run(main())
Security Best Practices
-
Key Management:
- Store SSH keys in standard locations (
~/.ssh/) - Use Ed25519 keys for better security
- Keep private keys protected (600 permissions)
- Store SSH keys in standard locations (
-
Error Handling:
try: ssh_agent = PersistentSSHAgent() success = ssh_agent.setup_ssh('github.com') if not success: print("โ ๏ธ SSH setup failed") except Exception as e: print(f"โ Error: {e}")
-
Session Management:
- Agent information persists across sessions
- Automatic cleanup of expired sessions
- Configurable expiration time
- Multi-session concurrent management
-
Security Features:
- Automatic key unloading after expiration
- Secure temporary file handling
- Platform-specific security measures
- Key usage tracking
๐ง Common Use Cases
Command Line Interface (CLI)
The library provides a command-line interface for easy configuration and testing:
# Configure SSH agent with a specific identity file
uvx persistent_ssh_agent config --identity-file ~/.ssh/id_ed25519 --prompt-passphrase
# Test SSH connection to a host
uvx persistent_ssh_agent test github.com
# List configured SSH keys
uvx persistent_ssh_agent list
# Remove a specific SSH key
uvx persistent_ssh_agent remove --name github
# Export configuration to a file
uvx persistent_ssh_agent export --output ~/.ssh/config.json
# Import configuration from a file
uvx persistent_ssh_agent import config.json
# Set up Git credentials (new feature)
uvx persistent_ssh_agent git-setup --username your-username --prompt
Available commands:
-
config: Configure SSH agent settings--identity-file: Path to SSH identity file--passphrase: SSH key passphrase (not recommended, use --prompt-passphrase instead)--prompt-passphrase: Prompt for SSH key passphrase--expiration: Expiration time in hours--reuse-agent: Whether to reuse existing SSH agent
-
test: Test SSH connection to a hosthostname: Hostname to test connection with--identity-file: Path to SSH identity file (overrides config)--expiration: Expiration time in hours (overrides config)--reuse-agent: Whether to reuse existing SSH agent (overrides config)--verbose: Enable verbose output
-
list: List configured SSH keys -
remove: Remove configured SSH keys--name: Name of the key to remove--all: Remove all keys
-
export: Export configuration--output: Output file path--include-sensitive: Include sensitive information in export
-
import: Import configurationinput_file: Input file path
-
git-setup: Configure Git credentials--username: Git username--password: Git password (not recommended, use --prompt instead)--prompt: Prompt for Git credentials interactively
CI/CD Pipeline Integration
from persistent_ssh_agent import PersistentSSHAgent
from persistent_ssh_agent.config import SSHConfig
def setup_ci_ssh():
"""Set up SSH for CI environment."""
# Create configuration with key content
config = SSHConfig(
identity_content=os.environ.get('SSH_PRIVATE_KEY'),
ssh_options={'BatchMode': 'yes'}
)
ssh_agent = PersistentSSHAgent(config=config)
if ssh_agent.setup_ssh('github.com'):
print("โ
SSH agent started successfully")
return True
raise RuntimeError("Failed to start SSH agent")
Git Integration
from git import Repo
from persistent_ssh_agent import PersistentSSHAgent
import os
def clone_repo(repo_url: str, local_path: str) -> Repo:
"""Clone a repository using persistent SSH authentication."""
ssh_agent = PersistentSSHAgent()
# Extract hostname and set up SSH
hostname = ssh_agent.extract_hostname(repo_url)
if not hostname or not ssh_agent.setup_ssh(hostname):
raise RuntimeError("Failed to set up SSH authentication")
# Get SSH command and configure environment
ssh_command = ssh_agent.get_git_ssh_command(hostname)
if not ssh_command:
raise RuntimeError("Failed to get SSH command")
# Clone with GitPython
env = os.environ.copy()
env['GIT_SSH_COMMAND'] = ssh_command
return Repo.clone_from(
repo_url,
local_path,
env=env
)
Git Credential Helper Support (Simplified)
You can now set up Git credentials in a simplified way without manual script creation:
from persistent_ssh_agent import PersistentSSHAgent
# Method 1: Set credentials directly
ssh_agent = PersistentSSHAgent()
ssh_agent.git.setup_git_credentials('your-username', 'your-password')
# Method 2: Use environment variables
import os
os.environ['GIT_USERNAME'] = 'your-username'
os.environ['GIT_PASSWORD'] = 'your-password'
ssh_agent.git.setup_git_credentials() # Automatically reads from env vars
# Now Git commands will use these credentials
CLI Setup:
# Set credentials directly
uvx persistent_ssh_agent git-setup --username your-username --password your-password
# Interactive setup
uvx persistent_ssh_agent git-setup --prompt
# Using environment variables
export GIT_USERNAME=your-username
export GIT_PASSWORD=your-password
uvx persistent_ssh_agent git-setup
CI Environment Usage:
# In build scripts
from persistent_ssh_agent import PersistentSSHAgent
# Use context manager
with PersistentSSHAgent() as agent:
# SSH and Git credentials are configured, ready for Git operations
agent.setup_ssh('github.com')
# Execute any Git commands...
๐ Advanced Features
Custom Configuration
from persistent_ssh_agent import PersistentSSHAgent
from persistent_ssh_agent.config import SSHConfig
# Create config instance
config = SSHConfig()
# Add global configuration
config.add_global_config({
'AddKeysToAgent': 'yes',
'UseKeychain': 'yes'
})
# Add host-specific configuration
config.add_host_config('*.github.com', {
'User': 'git',
'IdentityFile': '~/.ssh/github_ed25519',
'PreferredAuthentications': 'publickey'
})
# Initialize agent with config
agent = PersistentSSHAgent(config=config)
Key Management
The library automatically manages SSH keys based on your SSH configuration:
from persistent_ssh_agent import PersistentSSHAgent
from persistent_ssh_agent.config import SSHConfig
# Use specific key
config = SSHConfig(identity_file='~/.ssh/id_ed25519')
agent = PersistentSSHAgent(config=config)
# Or let the library automatically detect and use available keys
agent = PersistentSSHAgent()
if agent.setup_ssh('github.com'):
print("โ
SSH key loaded and ready!")
The library supports the following key types in order of preference:
- Ed25519 (recommended, most secure)
- ECDSA
- ECDSA with security key
- Ed25519 with security key
- RSA
- DSA (legacy, not recommended)
SSH Configuration Validation
The library provides comprehensive SSH configuration validation with support for:
from persistent_ssh_agent import PersistentSSHAgent
from persistent_ssh_agent.config import SSHConfig
# Create custom SSH configuration with validation
config = SSHConfig()
# Add host configuration with various options
config.add_host_config('github.com', {
# Connection Settings
'IdentityFile': '~/.ssh/github_key',
'User': 'git',
'Port': '22',
# Security Settings
'StrictHostKeyChecking': 'yes',
'PasswordAuthentication': 'no',
'PubkeyAuthentication': 'yes',
# Connection Optimization
'Compression': 'yes',
'ConnectTimeout': '60',
'ServerAliveInterval': '60',
'ServerAliveCountMax': '3',
# Proxy and Forwarding
'ProxyCommand': 'ssh -W %h:%p bastion',
'ForwardAgent': 'yes'
})
# Initialize with validated config
ssh_agent = PersistentSSHAgent(config=config)
Supported configuration categories:
- Connection Settings: Port, Hostname, User, IdentityFile
- Security Settings: StrictHostKeyChecking, BatchMode, PasswordAuthentication
- Connection Optimization: Compression, ConnectTimeout, ServerAliveInterval
- Proxy and Forwarding: ProxyCommand, ForwardAgent, ForwardX11
- Environment Settings: RequestTTY, SendEnv
- Multiplexing Options: ControlMaster, ControlPath, ControlPersist
For detailed validation rules and supported options, see SSH Configuration Validation
SSH Key Types Support
The library supports multiple SSH key types:
- Ed25519 (recommended, most secure)
- ECDSA
- ECDSA with security key
- Ed25519 with security key
- RSA
- DSA (legacy, not recommended)
Security Features
-
SSH Key Management:
- Automatic detection and loading of SSH keys (Ed25519, ECDSA, RSA)
- Support for key content injection (useful in CI/CD)
- Secure key file permissions handling
- Optional passphrase support
-
Configuration Security:
- Strict hostname validation
- Secure default settings
- Support for security-focused SSH options
-
Session Management:
- Secure storage of agent information
- Platform-specific security measures
- Automatic cleanup of expired sessions
- Cross-platform compatibility
Type Hints Support
The library provides comprehensive type hints for all public interfaces:
from typing import Optional
from persistent_ssh_agent import PersistentSSHAgent
from persistent_ssh_agent.config import SSHConfig
def setup_ssh(hostname: str, key_file: Optional[str] = None) -> bool:
config = SSHConfig(identity_file=key_file)
agent = PersistentSSHAgent(config=config)
return agent.setup_ssh(hostname)
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file persistent_ssh_agent-0.8.0.tar.gz.
File metadata
- Download URL: persistent_ssh_agent-0.8.0.tar.gz
- Upload date:
- Size: 33.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b70309eb24896173bf851374dec640acefc9ac2f9a4031e5d29f76b55e2345da
|
|
| MD5 |
87abcbcbe80caca44b57c985feb65c68
|
|
| BLAKE2b-256 |
e7a4d25c0171df6927aa83bf473a2403fb65ba12041f8a004c08d3e15043df99
|
Provenance
The following attestation bundles were made for persistent_ssh_agent-0.8.0.tar.gz:
Publisher:
python-publish.yml on loonghao/persistent_ssh_agent
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
persistent_ssh_agent-0.8.0.tar.gz -
Subject digest:
b70309eb24896173bf851374dec640acefc9ac2f9a4031e5d29f76b55e2345da - Sigstore transparency entry: 218999046
- Sigstore integration time:
-
Permalink:
loonghao/persistent_ssh_agent@5f43dd44aa117642a44e7959a4b523b6c62296e6 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/loonghao
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@5f43dd44aa117642a44e7959a4b523b6c62296e6 -
Trigger Event:
repository_dispatch
-
Statement type:
File details
Details for the file persistent_ssh_agent-0.8.0-py3-none-any.whl.
File metadata
- Download URL: persistent_ssh_agent-0.8.0-py3-none-any.whl
- Upload date:
- Size: 34.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
804b1e1c62c69c4a8cc3986d7f064b2b20afad995ee7a8a8f533b680f86d6c4e
|
|
| MD5 |
8f3e96195961f3719efd0818aa6c54d8
|
|
| BLAKE2b-256 |
879697a7b9e8482e89b545137c5dd4ca08ce3028f427ad62aaaee62a88e8f899
|
Provenance
The following attestation bundles were made for persistent_ssh_agent-0.8.0-py3-none-any.whl:
Publisher:
python-publish.yml on loonghao/persistent_ssh_agent
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
persistent_ssh_agent-0.8.0-py3-none-any.whl -
Subject digest:
804b1e1c62c69c4a8cc3986d7f064b2b20afad995ee7a8a8f533b680f86d6c4e - Sigstore transparency entry: 218999060
- Sigstore integration time:
-
Permalink:
loonghao/persistent_ssh_agent@5f43dd44aa117642a44e7959a4b523b6c62296e6 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/loonghao
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@5f43dd44aa117642a44e7959a4b523b6c62296e6 -
Trigger Event:
repository_dispatch
-
Statement type: