persistent-ssh-agent


Namepersistent-ssh-agent JSON
Version 0.5.1 PyPI version JSON
download
home_pageNone
SummaryA Python library for persistent SSH agent management with automatic key handling, focusing on Windows compatibility and seamless Git integration.
upload_time2024-12-28 14:49:02
maintainerNone
docs_urlNone
authorlonghao
requires_python<4.0,>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # persistent-ssh-agent

[![Python Version](https://img.shields.io/pypi/pyversions/persistent_ssh_agent)](https://img.shields.io/pypi/pyversions/persistent_ssh_agent)
[![Nox](https://img.shields.io/badge/%F0%9F%A6%8A-Nox-D85E00.svg)](https://github.com/wntrblm/nox)
[![PyPI Version](https://img.shields.io/pypi/v/persistent_ssh_agent?color=green)](https://pypi.org/project/persistent_ssh_agent/)
[![Downloads](https://static.pepy.tech/badge/persistent_ssh_agent)](https://pepy.tech/project/persistent_ssh_agent)
[![Downloads](https://static.pepy.tech/badge/persistent_ssh_agent/month)](https://pepy.tech/project/persistent_ssh_agent)
[![Downloads](https://static.pepy.tech/badge/persistent_ssh_agent/week)](https://pepy.tech/project/persistent_ssh_agent)
[![License](https://img.shields.io/pypi/l/persistent_ssh_agent)](https://pypi.org/project/persistent_ssh_agent/)
[![PyPI Format](https://img.shields.io/pypi/format/persistent_ssh_agent)](https://pypi.org/project/persistent_ssh_agent/)
[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/loonghao/persistent_ssh_agent/graphs/commit-activity)
[![Codecov](https://img.shields.io/codecov/c/github/loonghao/persistent_ssh_agent)](https://codecov.io/gh/loonghao/persistent_ssh_agent)

[English](./README.md) | [δΈ­ζ–‡](./README_zh.md)

πŸ” A modern Python library for persistent SSH agent management across sessions.

## πŸ“š Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
- [Security Features](#security-features)
- [Contributing](#contributing)

## ✨ 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
- ⚑ 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)

## πŸš€ Installation

```bash
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

```python
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

```python
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:

```python
# Always start a new agent session
ssh_agent = PersistentSSHAgent(reuse_agent=False)
```

### Multiple Host Configuration

```python
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

```python
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

```python
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

1. **Key Management**:
   - Store SSH keys in standard locations (`~/.ssh/`)
   - Use Ed25519 keys for better security
   - Keep private keys protected (600 permissions)

2. **Error Handling**:

   ```python
   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}")
   ```

3. **Session Management**:
   - Agent information persists across sessions
   - Automatic cleanup of expired sessions
   - Configurable expiration time
   - Multi-session concurrent management

4. **Security Features**:
   - Automatic key unloading after expiration
   - Secure temporary file handling
   - Platform-specific security measures
   - Key usage tracking

## πŸ”§ Common Use Cases

### CI/CD Pipeline Integration

```python
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

```python
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
    )
```

## 🌟 Advanced Features

### Custom Configuration

```python
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:

```python
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:

```python
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-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

1. **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

2. **Configuration Security**:

   - Strict hostname validation
   - Secure default settings
   - Support for security-focused SSH options

3. **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:

```python
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.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## πŸ“„ License

This project is licensed under the MIT License - see the [LICENSE](#license) file for details.


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "persistent-ssh-agent",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "longhao",
    "author_email": "hal.long@outlook.com",
    "download_url": "https://files.pythonhosted.org/packages/b2/cb/0464b605a48197eff349e1a9d174d092e88a316562f8ef90caf72ee3d7d7/persistent_ssh_agent-0.5.1.tar.gz",
    "platform": null,
    "description": "# persistent-ssh-agent\n\n[![Python Version](https://img.shields.io/pypi/pyversions/persistent_ssh_agent)](https://img.shields.io/pypi/pyversions/persistent_ssh_agent)\n[![Nox](https://img.shields.io/badge/%F0%9F%A6%8A-Nox-D85E00.svg)](https://github.com/wntrblm/nox)\n[![PyPI Version](https://img.shields.io/pypi/v/persistent_ssh_agent?color=green)](https://pypi.org/project/persistent_ssh_agent/)\n[![Downloads](https://static.pepy.tech/badge/persistent_ssh_agent)](https://pepy.tech/project/persistent_ssh_agent)\n[![Downloads](https://static.pepy.tech/badge/persistent_ssh_agent/month)](https://pepy.tech/project/persistent_ssh_agent)\n[![Downloads](https://static.pepy.tech/badge/persistent_ssh_agent/week)](https://pepy.tech/project/persistent_ssh_agent)\n[![License](https://img.shields.io/pypi/l/persistent_ssh_agent)](https://pypi.org/project/persistent_ssh_agent/)\n[![PyPI Format](https://img.shields.io/pypi/format/persistent_ssh_agent)](https://pypi.org/project/persistent_ssh_agent/)\n[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/loonghao/persistent_ssh_agent/graphs/commit-activity)\n[![Codecov](https://img.shields.io/codecov/c/github/loonghao/persistent_ssh_agent)](https://codecov.io/gh/loonghao/persistent_ssh_agent)\n\n[English](./README.md) | [\u4e2d\u6587](./README_zh.md)\n\n\ud83d\udd10 A modern Python library for persistent SSH agent management across sessions.\n\n## \ud83d\udcda Table of Contents\n\n- [Features](#features)\n- [Installation](#installation)\n- [Usage](#usage)\n- [Security Features](#security-features)\n- [Contributing](#contributing)\n\n## \u2728 Features\n\n- \ud83d\udd04 Persistent SSH agent management across sessions\n- \ud83d\udd11 Automatic SSH key loading and caching\n- \ud83e\ude9f Windows-optimized implementation\n- \ud83d\udd17 Seamless Git integration\n- \ud83c\udf10 Cross-platform compatibility (Windows, Linux, macOS)\n- \ud83d\udce6 No external dependencies beyond standard SSH tools\n- \ud83d\udd12 Secure key management and session control\n- \u26a1 Asynchronous operation support\n- \ud83e\uddea Complete unit test coverage with performance benchmarks\n- \ud83d\udcdd Comprehensive type hints support\n- \ud83d\udd10 Support for multiple SSH key types (Ed25519, ECDSA, RSA)\n- \ud83c\udf0d IPv6 support\n- \ud83d\udcda Multi-language documentation support\n- \ud83d\udd0d Enhanced SSH configuration validation\n- \ud83d\udee0\ufe0f Modern development toolchain (Poetry, Commitizen, Black)\n\n## \ud83d\ude80 Installation\n\n```bash\npip install persistent-ssh-agent\n```\n\n## \ud83d\udccb Requirements\n\n- Python 3.8-3.13\n- OpenSSH (ssh-agent, ssh-add) installed and available in PATH\n- Git (optional, for Git operations)\n\n## \ud83d\udcd6 Usage\n\n### Basic Usage\n\n```python\nfrom persistent_ssh_agent import PersistentSSHAgent\n\n# Create an instance with custom expiration time (default is 24 hours)\nssh_agent = PersistentSSHAgent(expiration_time=86400)\n\n# Set up SSH for a specific host\nif ssh_agent.setup_ssh('github.com'):\n    print(\"\u2705 SSH authentication ready!\")\n```\n\n### Advanced Configuration\n\n```python\nfrom persistent_ssh_agent import PersistentSSHAgent\nfrom persistent_ssh_agent.config import SSHConfig\n\n# Create custom SSH configuration\nconfig = SSHConfig(\n    identity_file='~/.ssh/github_key',  # Optional specific identity file\n    identity_passphrase='your-passphrase',  # Optional passphrase\n    ssh_options={  # Optional SSH options\n        'StrictHostKeyChecking': 'yes',\n        'PasswordAuthentication': 'no',\n        'PubkeyAuthentication': 'yes'\n    }\n)\n\n# Initialize with custom config and agent reuse settings\nssh_agent = PersistentSSHAgent(\n    config=config,\n    expiration_time=86400,  # Optional: Set agent expiration time (default 24 hours)\n    reuse_agent=True  # Optional: Control agent reuse behavior (default True)\n)\n\n# Set up SSH authentication\nif ssh_agent.setup_ssh('github.com'):\n    # Get Git SSH command for the host\n    ssh_command = ssh_agent.get_git_ssh_command('github.com')\n    if ssh_command:\n        print(\"\u2705 Git SSH command ready!\")\n```\n\n### Agent Reuse Behavior\n\nThe `reuse_agent` parameter controls how the SSH agent handles existing sessions:\n\n- When `reuse_agent=True` (default):\n  - Attempts to reuse an existing SSH agent if available\n  - Reduces the number of agent startups and key additions\n  - Improves performance by avoiding unnecessary agent operations\n\n- When `reuse_agent=False`:\n  - Always starts a new SSH agent session\n  - Useful when you need a fresh agent state\n  - May be preferred in certain security-sensitive environments\n\nExample with agent reuse disabled:\n\n```python\n# Always start a new agent session\nssh_agent = PersistentSSHAgent(reuse_agent=False)\n```\n\n### Multiple Host Configuration\n\n```python\nfrom persistent_ssh_agent import PersistentSSHAgent\nfrom persistent_ssh_agent.config import SSHConfig\n\n# Create configuration with common options\nconfig = SSHConfig(\n    ssh_options={\n        'BatchMode': 'yes',\n        'StrictHostKeyChecking': 'yes',\n        'ServerAliveInterval': '60'\n    }\n)\n\n# Initialize agent\nagent = PersistentSSHAgent(config=config)\n\n# Set up SSH for multiple hosts\nhosts = ['github.com', 'gitlab.com', 'bitbucket.org']\nfor host in hosts:\n    if agent.setup_ssh(host):\n        print(f\"\u2705 SSH configured for {host}\")\n    else:\n        print(f\"\u274c Failed to configure SSH for {host}\")\n```\n\n### Global SSH Configuration\n\n```python\nfrom persistent_ssh_agent import PersistentSSHAgent\nfrom persistent_ssh_agent.config import SSHConfig\n\n# Create configuration with global options\nconfig = SSHConfig(\n    # Set identity file (optional)\n    identity_file='~/.ssh/id_ed25519',\n\n    # Set global SSH options\n    ssh_options={\n        'StrictHostKeyChecking': 'yes',\n        'PasswordAuthentication': 'no',\n        'PubkeyAuthentication': 'yes',\n        'BatchMode': 'yes',\n        'ConnectTimeout': '30'\n    }\n)\n\n# Initialize agent with global configuration\nagent = PersistentSSHAgent(config=config)\n```\n\n### Asynchronous Support\n\n```python\nimport asyncio\nfrom persistent_ssh_agent import PersistentSSHAgent\n\nasync def setup_multiple_hosts(hosts: list[str]) -> dict[str, bool]:\n    \"\"\"Set up SSH for multiple hosts concurrently.\"\"\"\n    ssh_agent = PersistentSSHAgent()\n    results = {}\n\n    async def setup_host(host: str):\n        results[host] = await ssh_agent.async_setup_ssh(host)\n\n    await asyncio.gather(*[setup_host(host) for host in hosts])\n    return results\n\n# Usage example\nasync def main():\n    hosts = ['github.com', 'gitlab.com', 'bitbucket.org']\n    results = await setup_multiple_hosts(hosts)\n    for host, success in results.items():\n        print(f\"{host}: {'\u2705' if success else '\u274c'}\")\n\nasyncio.run(main())\n```\n\n### Security Best Practices\n\n1. **Key Management**:\n   - Store SSH keys in standard locations (`~/.ssh/`)\n   - Use Ed25519 keys for better security\n   - Keep private keys protected (600 permissions)\n\n2. **Error Handling**:\n\n   ```python\n   try:\n       ssh_agent = PersistentSSHAgent()\n       success = ssh_agent.setup_ssh('github.com')\n       if not success:\n           print(\"\u26a0\ufe0f SSH setup failed\")\n   except Exception as e:\n       print(f\"\u274c Error: {e}\")\n   ```\n\n3. **Session Management**:\n   - Agent information persists across sessions\n   - Automatic cleanup of expired sessions\n   - Configurable expiration time\n   - Multi-session concurrent management\n\n4. **Security Features**:\n   - Automatic key unloading after expiration\n   - Secure temporary file handling\n   - Platform-specific security measures\n   - Key usage tracking\n\n## \ud83d\udd27 Common Use Cases\n\n### CI/CD Pipeline Integration\n\n```python\nfrom persistent_ssh_agent import PersistentSSHAgent\nfrom persistent_ssh_agent.config import SSHConfig\n\ndef setup_ci_ssh():\n    \"\"\"Set up SSH for CI environment.\"\"\"\n    # Create configuration with key content\n    config = SSHConfig(\n        identity_content=os.environ.get('SSH_PRIVATE_KEY'),\n        ssh_options={'BatchMode': 'yes'}\n    )\n\n    ssh_agent = PersistentSSHAgent(config=config)\n\n    if ssh_agent.setup_ssh('github.com'):\n        print(\"\u2705 SSH agent started successfully\")\n        return True\n\n    raise RuntimeError(\"Failed to start SSH agent\")\n```\n\n### Git Integration\n\n```python\nfrom git import Repo\nfrom persistent_ssh_agent import PersistentSSHAgent\nimport os\n\ndef clone_repo(repo_url: str, local_path: str) -> Repo:\n    \"\"\"Clone a repository using persistent SSH authentication.\"\"\"\n    ssh_agent = PersistentSSHAgent()\n\n    # Extract hostname and set up SSH\n    hostname = ssh_agent._extract_hostname(repo_url)\n    if not hostname or not ssh_agent.setup_ssh(hostname):\n        raise RuntimeError(\"Failed to set up SSH authentication\")\n\n    # Get SSH command and configure environment\n    ssh_command = ssh_agent.get_git_ssh_command(hostname)\n    if not ssh_command:\n        raise RuntimeError(\"Failed to get SSH command\")\n\n    # Clone with GitPython\n    env = os.environ.copy()\n    env['GIT_SSH_COMMAND'] = ssh_command\n\n    return Repo.clone_from(\n        repo_url,\n        local_path,\n        env=env\n    )\n```\n\n## \ud83c\udf1f Advanced Features\n\n### Custom Configuration\n\n```python\nfrom persistent_ssh_agent import PersistentSSHAgent\nfrom persistent_ssh_agent.config import SSHConfig\n\n# Create config instance\nconfig = SSHConfig()\n\n# Add global configuration\nconfig.add_global_config({\n    'AddKeysToAgent': 'yes',\n    'UseKeychain': 'yes'\n})\n\n# Add host-specific configuration\nconfig.add_host_config('*.github.com', {\n    'User': 'git',\n    'IdentityFile': '~/.ssh/github_ed25519',\n    'PreferredAuthentications': 'publickey'\n})\n\n# Initialize agent with config\nagent = PersistentSSHAgent(config=config)\n```\n\n### Key Management\n\nThe library automatically manages SSH keys based on your SSH configuration:\n\n```python\nfrom persistent_ssh_agent import PersistentSSHAgent\nfrom persistent_ssh_agent.config import SSHConfig\n\n# Use specific key\nconfig = SSHConfig(identity_file='~/.ssh/id_ed25519')\nagent = PersistentSSHAgent(config=config)\n\n# Or let the library automatically detect and use available keys\nagent = PersistentSSHAgent()\nif agent.setup_ssh('github.com'):\n    print(\"\u2705 SSH key loaded and ready!\")\n```\n\nThe library supports the following key types in order of preference:\n\n- Ed25519 (recommended, most secure)\n- ECDSA\n- ECDSA with security key\n- Ed25519 with security key\n- RSA\n- DSA (legacy, not recommended)\n\n### SSH Configuration Validation\n\nThe library provides comprehensive SSH configuration validation with support for:\n\n```python\nfrom persistent_ssh_agent import PersistentSSHAgent\nfrom persistent_ssh_agent.config import SSHConfig\n\n# Create custom SSH configuration with validation\nconfig = SSHConfig()\n\n# Add host configuration with various options\nconfig.add_host_config('github.com', {\n    # Connection Settings\n    'IdentityFile': '~/.ssh/github_key',\n    'User': 'git',\n    'Port': '22',\n\n    # Security Settings\n    'StrictHostKeyChecking': 'yes',\n    'PasswordAuthentication': 'no',\n    'PubkeyAuthentication': 'yes',\n\n    # Connection Optimization\n    'Compression': 'yes',\n    'ConnectTimeout': '60',\n    'ServerAliveInterval': '60',\n    'ServerAliveCountMax': '3',\n\n    # Proxy and Forwarding\n    'ProxyCommand': 'ssh -W %h:%p bastion',\n    'ForwardAgent': 'yes'\n})\n\n# Initialize with validated config\nssh_agent = PersistentSSHAgent(config=config)\n```\n\nSupported configuration categories:\n\n- **Connection Settings**: Port, Hostname, User, IdentityFile\n- **Security Settings**: StrictHostKeyChecking, BatchMode, PasswordAuthentication\n- **Connection Optimization**: Compression, ConnectTimeout, ServerAliveInterval\n- **Proxy and Forwarding**: ProxyCommand, ForwardAgent, ForwardX11\n- **Environment Settings**: RequestTTY, SendEnv\n- **Multiplexing Options**: ControlMaster, ControlPath, ControlPersist\n\nFor detailed validation rules and supported options, see [SSH Configuration Validation](#ssh-configuration-validation)\n\n### SSH Key Types Support\n\nThe library supports multiple SSH key types:\n\n- Ed25519 (recommended, most secure)\n- ECDSA\n- ECDSA with security key\n- Ed25519 with security key\n- RSA\n- DSA (legacy, not recommended)\n\n### Security Features\n\n1. **SSH Key Management**:\n\n   - Automatic detection and loading of SSH keys (Ed25519, ECDSA, RSA)\n   - Support for key content injection (useful in CI/CD)\n   - Secure key file permissions handling\n   - Optional passphrase support\n\n2. **Configuration Security**:\n\n   - Strict hostname validation\n   - Secure default settings\n   - Support for security-focused SSH options\n\n3. **Session Management**:\n\n   - Secure storage of agent information\n   - Platform-specific security measures\n   - Automatic cleanup of expired sessions\n   - Cross-platform compatibility\n\n### Type Hints Support\n\nThe library provides comprehensive type hints for all public interfaces:\n\n```python\nfrom typing import Optional\nfrom persistent_ssh_agent import PersistentSSHAgent\nfrom persistent_ssh_agent.config import SSHConfig\n\ndef setup_ssh(hostname: str, key_file: Optional[str] = None) -> bool:\n    config = SSHConfig(identity_file=key_file)\n    agent = PersistentSSHAgent(config=config)\n    return agent.setup_ssh(hostname)\n```\n\n## \ud83e\udd1d Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](#license) file for details.\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A Python library for persistent SSH agent management with automatic key handling, focusing on Windows compatibility and seamless Git integration.",
    "version": "0.5.1",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bf451337350df57d308250499de4b39a52cd03cbaf2324a7d05d5a06dfb5571a",
                "md5": "d47768fbc3cc2063e8a8fc2e50591441",
                "sha256": "be26ec90fec1bfbb4945b569a8bd960f863011f141438c6164604fa02c944160"
            },
            "downloads": -1,
            "filename": "persistent_ssh_agent-0.5.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d47768fbc3cc2063e8a8fc2e50591441",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 16042,
            "upload_time": "2024-12-28T14:49:00",
            "upload_time_iso_8601": "2024-12-28T14:49:00.120741Z",
            "url": "https://files.pythonhosted.org/packages/bf/45/1337350df57d308250499de4b39a52cd03cbaf2324a7d05d5a06dfb5571a/persistent_ssh_agent-0.5.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b2cb0464b605a48197eff349e1a9d174d092e88a316562f8ef90caf72ee3d7d7",
                "md5": "411a97feb658a12ab2a4ca718eae9ec8",
                "sha256": "996f30221df1fde031b1b94fdd285b65188490e4dcc43c9d1c405a3342fbbfdd"
            },
            "downloads": -1,
            "filename": "persistent_ssh_agent-0.5.1.tar.gz",
            "has_sig": false,
            "md5_digest": "411a97feb658a12ab2a4ca718eae9ec8",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 19440,
            "upload_time": "2024-12-28T14:49:02",
            "upload_time_iso_8601": "2024-12-28T14:49:02.752833Z",
            "url": "https://files.pythonhosted.org/packages/b2/cb/0464b605a48197eff349e1a9d174d092e88a316562f8ef90caf72ee3d7d7/persistent_ssh_agent-0.5.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-28 14:49:02",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "persistent-ssh-agent"
}
        
Elapsed time: 1.34992s