Skip to main content

Python wrapper for kytan VPN - High Performance Peer-to-Peer VPN

Project description

kytan-py: Python Wrapper for kytan VPN

A Python interface to the kytan high-performance peer-to-peer VPN application.

Features

  • Easy Integration: Simple Python API for embedding VPN functionality in applications
  • Client & Server Support: Both client and server modes supported
  • Process Management: Automatic process lifecycle management with proper cleanup
  • Logging Integration: Built-in logging support with configurable levels
  • Context Manager Support: Use with with statements for automatic cleanup
  • Command Line Interface: Can be used as a standalone CLI tool
  • Self-Contained: Automatically builds and bundles the kytan binary during installation

Requirements

  • Python 3.7+
  • Rust/Cargo (for building during installation)
  • Root/sudo privileges (required by kytan)
  • Linux (server mode) or Linux/macOS (client mode)

Installation

The package will automatically build the kytan Rust binary during installation:

# Install from source (builds kytan binary automatically)
cd kytan-py
pip install .

# Install in development mode (builds kytan binary automatically)
pip install -e .

# Install with development dependencies
pip install -e ".[dev]"

Build Requirements

During installation, the package will:

  1. Check for Rust/Cargo availability
  2. Build the kytan binary from source using cargo build --release
  3. Bundle the binary with the Python package
  4. Make it available to the Python wrapper

If you don't have Rust installed, you can install it from https://rustup.rs/.

Quick Start

As a Python Library

Client Mode

from kytan import create_client

# Create and connect client (uses bundled kytan binary automatically)
client = create_client()
client.connect(
    server="your-server.com",
    port=9527,
    key="your-secret-key"
)

# Check status
status = client.get_status()
print(f"Connected: {status['running']}")

# Disconnect
client.disconnect()

Server Mode

from kytan import create_server

# Create and start server (uses bundled kytan binary automatically)
server = create_server()
server.serve(
    port=9527,
    key="your-secret-key",
    bind="0.0.0.0",
    dns="8.8.8.8"
)

# Check status
status = server.get_status()
print(f"Server running: {status['running']}")

# Shutdown
server.shutdown()

Using Context Managers

from kytan import create_client, KytanContextManager

# Automatic cleanup when exiting context
with KytanContextManager(create_client()) as client:
    client.connect("server.com", 9527, "secret-key")
    # Do work...
    # Client automatically disconnects when exiting

As a Command Line Tool

# Client mode (uses bundled binary)
sudo kytan-py client -s server.com -p 9527 -k secret-key

# Server mode  
sudo kytan-py server -p 9527 -k secret-key -d 8.8.8.8

# With custom log level
sudo RUST_LOG=debug kytan-py client -s server.com -p 9527 -k secret-key --log-level debug

API Reference

Classes

KytanClient

Main client class for connecting to kytan VPN servers.

Methods:

  • connect(server, port, key, no_default_route=False, log_level="info"): Connect to server
  • disconnect(timeout=10): Disconnect from server
  • get_status(): Get connection status
  • get_logs(lines=50): Get recent log output

KytanServer

Main server class for running kytan VPN servers.

Methods:

  • serve(port=9527, key="", bind="0.0.0.0", dns="8.8.8.8", log_level="info"): Start server
  • shutdown(timeout=10): Shutdown server
  • get_status(): Get server status
  • get_logs(lines=50): Get recent log output

ClientConfig / ServerConfig

Configuration dataclasses for client and server settings.

Functions

  • create_client(binary_path=None): Create a new client instance
  • create_server(binary_path=None): Create a new server instance

Exceptions

  • KytanError: Base exception for kytan-related errors

Configuration

Binary Path

The wrapper will automatically use the bundled kytan binary that was built during installation. If you need to use a different binary, you can specify a custom path:

client = create_client(binary_path="/path/to/custom/kytan")

The search order is:

  1. Bundled binary (built during pip install)
  2. Custom path if specified
  3. PATH environment variable
  4. Common system locations

Logging

Set the RUST_LOG environment variable or use the log_level parameter:

# Environment variable
import os
os.environ['RUST_LOG'] = 'debug'

# Or via parameter
client.connect(server="...", port=9527, key="...", log_level="debug")

Available log levels: error, warn, info, debug, trace

Development

Building from Source

If you're developing or want to build manually:

# Clone the repository
git clone https://github.com/changlan/kytan.git
cd kytan

# Install in development mode (builds kytan automatically)
cd kytan-py
pip install -e .

# Or build kytan manually first
cd ..
cargo build --release
cd kytan-py
pip install -e .

Running Tests

# Install with development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run with coverage
pytest --cov=kytan

Examples

Advanced Client Usage

import time
import logging
from kytan import create_client, KytanError

# Set up logging
logging.basicConfig(level=logging.INFO)

try:
    # Uses bundled binary automatically
    client = create_client()
    
    # Connect with custom settings
    client.connect(
        server="vpn.example.com",
        port=9527,
        key="my-secret-key",
        no_default_route=True,  # Don't change default route
        log_level="info"
    )
    
    print("Connected successfully!")
    
    # Monitor connection
    while True:
        status = client.get_status()
        if not status["running"]:
            print("Connection lost!")
            break
        
        print(f"Status: Connected (PID: {status['pid']})")
        time.sleep(10)
        
except KytanError as e:
    print(f"VPN Error: {e}")
except KeyboardInterrupt:
    print("Disconnecting...")
finally:
    client.disconnect()

Server with Custom DNS

from kytan import create_server

# Uses bundled binary automatically
server = create_server()

try:
    server.serve(
        port=9527,
        key="server-secret-key",
        bind="0.0.0.0",
        dns="1.1.1.1",  # Use Cloudflare DNS
        log_level="info"
    )
    
    print("Server started on port 9527")
    
    # Keep server running
    while server.get_status()["running"]:
        time.sleep(1)
        
except KeyboardInterrupt:
    print("Shutting down server...")
finally:
    server.shutdown()

Security Notes

  • Always use strong, unique encryption keys
  • Run with minimal required privileges
  • Consider using a dedicated user account for VPN operations
  • Monitor logs for suspicious activity
  • Keep the package updated to get the latest kytan binary

Troubleshooting

Common Issues

  1. "Cargo (Rust) is required to build kytan"

  2. "Failed to build kytan"

    • Check that you have the necessary build dependencies
    • Ensure you're in the correct directory structure
    • Try building kytan manually first: cargo build --release
  3. "kytan requires root privileges"

    • Run with sudo or as root user
    • VPN operations require elevated privileges
  4. Connection timeouts

    • Check firewall settings
    • Verify server is running and accessible
    • Ensure correct port and encryption key

Debug Mode

Enable debug logging to troubleshoot issues:

client.connect(..., log_level="debug")

License

This Python wrapper follows the same Apache 2.0 license as the original kytan project.

Contributing

Contributions are welcome! Please ensure:

  • Code follows PEP 8 style guidelines
  • Include tests for new functionality
  • Update documentation as needed

Related Projects

  • kytan - The original Rust VPN implementation

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

kytan_py-0.1.0.tar.gz (1.2 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kytan_py-0.1.0-py3-none-any.whl (1.2 MB view details)

Uploaded Python 3

File details

Details for the file kytan_py-0.1.0.tar.gz.

File metadata

  • Download URL: kytan_py-0.1.0.tar.gz
  • Upload date:
  • Size: 1.2 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.2

File hashes

Hashes for kytan_py-0.1.0.tar.gz
Algorithm Hash digest
SHA256 674ec45ce33ac2c82dc536ea79069e623c2fca11b0109893620ad4a2cad8193f
MD5 4b44494461b6ea12943bb32d1d640fc4
BLAKE2b-256 b3607bb0cec6b7d33efee2f6c46b67b27f4e411f9a4737567a83fedfb8a2384d

See more details on using hashes here.

File details

Details for the file kytan_py-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: kytan_py-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 1.2 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.2

File hashes

Hashes for kytan_py-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2fb72c54a696237f3f7fe9fcfe963556e9da03b3e17656e087ef33458bbe6adf
MD5 f848b9f0c5219fb8f88581011aa84951
BLAKE2b-256 dc6fb3d4789ba79368ab5f2bddb9469316482184bbeb5ab391187f9075649b7f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page