sshconf: Lightweight SSH Config Library

0.2.7 · active · verified Thu Apr 16

sshconf is a Python library designed for reading and modifying your `~/.ssh/config` file in a non-intrusive way. It aims to keep the file's structure largely intact after modifications, providing a simple interface to manage SSH client configurations. The current version is 0.2.7. It has an irregular release cadence, with the last release in June 2024.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a new SSH configuration, add and modify host entries, and then write the configuration to a file. It uses `sshconf.empty()` to start a new configuration and `write()` to save it, avoiding modification of your actual `~/.ssh/config` file for safety. Remember that `save()` will overwrite the file it was read from.

import sshconf
import os

# Create a temporary config file for demonstration
temp_config_path = os.path.expanduser('~/.ssh/config_temp')

# Ensure the .ssh directory exists
os.makedirs(os.path.dirname(temp_config_path), exist_ok=True)

# Start with an empty configuration
config = sshconf.empty()

# Add a new host entry
config.add(
    'devserver',
    Hostname='192.168.1.100',
    User='devuser',
    IdentityFile=os.path.expanduser('~/.ssh/id_rsa_dev')
)

# Update an existing entry or add a new parameter
config.set(
    'devserver',
    Port=2222,
    ForwardAgent='yes'
)

# Add another host with minimal options
config.add(
    'testserver',
    Hostname='test.example.com',
    User='testuser'
)

# Remove a parameter from a host
config.unset('devserver', 'ForwardAgent')

# Get configuration for a host
host_config = config.host('devserver')
print(f"Devserver config: {host_config.to_dict()}")

# Write the changes to a new file (or save() to overwrite original)
config.write(temp_config_path)

print(f"SSH config written to: {temp_config_path}")
print("Contents of the temporary config file:")
with open(temp_config_path, 'r') as f:
    print(f.read())

# Clean up the temporary file (optional)
# os.remove(temp_config_path)

view raw JSON →