Skip to main content

MAXCONN

Português

Projeto criado por Marcos Max para ser uma biblioteca Python voltada a redes e infraestrutura.

A ideia do MAXCONN é juntar, aos poucos, as ferramentas que um engenheiro de redes ou DevOps usa no dia a dia para automatizar tarefas de rede: conexão em equipamentos, execução de comandos, leitura de saída, coleta de dados, validação, inventário e, mais adiante, módulos específicos para fornecedores.

O início do projeto é a camada de conexão. Hoje o MAXCONN já tem cliente SSH e Telnet feitos sobre sockets, sem usar Paramiko, Netmiko, Scrapli ou Telnetlib como cliente em runtime.

Exemplo:

import maxconn

with maxconn.connect(
    "192.0.2.10",
    protocol="ssh",
    username="admin",
    password="secret",
) as conn:
    result = conn.run("display version", prompt_markers=(">", "#"))
    print(result.text)

Instalação

Instalação para desenvolvimento:

git clone https://github.com/mmaxjr/maxconn
cd maxconn
pip install -e ".[dev]"
pytest -v
ruff check src tests

Instalação futura para uso normal:

pip install maxconn

Para usar SSH:

pip install "maxconn[ssh]"

Telnet não puxa dependências extras. SSH usa cryptography pelo extra ssh. Paramiko fica só nos testes, para subir um servidor SSH local e validar o cliente do MAXCONN contra uma implementação independente.

Uso Básico

Telnet:

import maxconn

with maxconn.connect(
    "192.0.2.20",
    protocol="telnet",
    username="admin",
    password="secret",
) as conn:
    result = conn.run("show status", prompt_markers=(">", "#"))
    print(result.text)

SSH:

import maxconn

with maxconn.connect(
    "192.0.2.30",
    protocol="ssh",
    username="admin",
    password="secret",
) as conn:
    result = conn.run("show version", prompt_markers=(">", "#"))
    print(result.text)

Para uso mais direto, Connection.send(), Connection.recv(), Connection.read_until() e Connection.send_command() continuam disponíveis.

Resultado de Comando

Connection.run() retorna um resultado com campos úteis:

result = conn.run("display version", prompt_markers=(">", "#"))

print(result.command)
print(result.text)
print(result.bytes)
print(result.elapsed)
print(result.exit_status)
print(result.ok)

result.ok é verdadeiro quando exit_status é None ou 0. Em sessões CLI interativas, como Telnet e shell SSH, geralmente não existe status de saída, então None é esperado.

Expect

Para automação guiada por prompt, use ExpectSession diretamente:

from maxconn.automation import ExpectSession, PromptProfile

expect = ExpectSession(conn, prompt_markers=PromptProfile.CISCO)
output = expect.run("show running-config", timeout=20.0)

ExpectSession faz o básico que uma CLI de equipamento costuma precisar:

  • espera por prompts
  • remove eco do comando
  • responde paginação simples, como --More--
  • inclui a saída parcial quando ocorre timeout

Timeouts

connect() aceita timeouts separados:

conn = maxconn.connect(
    "192.0.2.30",
    protocol="ssh",
    username="admin",
    password="secret",
    connect_timeout=5.0,
    auth_timeout=10.0,
    command_timeout=5.0,
    prompt_timeout=10.0,
)

O argumento antigo timeout= continua funcionando. Quando connect_timeout ou auth_timeout não são informados, timeout= é usado como padrão.

Logging

A execução de comandos registra eventos pelo logger maxconn.audit:

import logging

logging.basicConfig(level=logging.INFO)

Trechos sensíveis com palavras como password, secret, token ou key são redigidos antes de ir para o log.

Erros

Use a hierarquia de exceções do projeto:

import maxconn

try:
    with maxconn.connect(
        "192.0.2.30",
        protocol="ssh",
        username="admin",
        password="bad-password",
    ) as conn:
        print(conn.run("show status", prompt_markers=(">", "#")).text)
except maxconn.AuthenticationError:
    print("Login failed")
except maxconn.ConnectionTimeoutError:
    print("Connection timed out")
except maxconn.ProtocolError as exc:
    print(f"Protocol problem: {exc}")
except maxconn.MaxConnError as exc:
    print(f"maxconn error: {exc}")

Direção do Projeto

  • Não transformar o projeto em wrapper de Paramiko, Netmiko, Scrapli ou Telnetlib.
  • Manter dependências opcionais atrás de extras.
  • Deixar bytes crus disponíveis para quem precisa.
  • Dar uma API simples para o caso comum.
  • Testar com servidores locais de Telnet e SSH sempre que fizer sentido.

English

Project created by Marcos Max as a Python library for networking and infrastructure work.

MAXCONN is meant to grow into a practical toolkit for network engineers and DevOps engineers who automate network tasks: connecting to devices, running commands, reading output, collecting data, validating state, building inventory, and later adding vendor-specific modules.

The project starts with the connection layer. Today MAXCONN has SSH and Telnet clients built on top of sockets, without using Paramiko, Netmiko, Scrapli, or Telnetlib as runtime clients.

Example:

import maxconn

with maxconn.connect(
    "192.0.2.10",
    protocol="ssh",
    username="admin",
    password="secret",
) as conn:
    result = conn.run("display version", prompt_markers=(">", "#"))
    print(result.text)

Installation

Development install:

git clone https://github.com/mmaxjr/maxconn
cd maxconn
pip install -e ".[dev]"
pytest -v
ruff check src tests

Future regular install:

pip install maxconn

For SSH:

pip install "maxconn[ssh]"

Telnet does not pull extra runtime dependencies. SSH uses cryptography through the ssh extra. Paramiko is test-only and is used to run a local SSH server for integration tests.

Basic Usage

Telnet:

import maxconn

with maxconn.connect(
    "192.0.2.20",
    protocol="telnet",
    username="admin",
    password="secret",
) as conn:
    result = conn.run("show status", prompt_markers=(">", "#"))
    print(result.text)

SSH:

import maxconn

with maxconn.connect(
    "192.0.2.30",
    protocol="ssh",
    username="admin",
    password="secret",
) as conn:
    result = conn.run("show version", prompt_markers=(">", "#"))
    print(result.text)

For lower-level use, Connection.send(), Connection.recv(), Connection.read_until(), and Connection.send_command() are still available.

Command Result

Connection.run() returns a result object:

result = conn.run("display version", prompt_markers=(">", "#"))

print(result.command)
print(result.text)
print(result.bytes)
print(result.elapsed)
print(result.exit_status)
print(result.ok)

result.ok is true when exit_status is None or 0. Interactive CLI sessions, such as Telnet and shell-style SSH, usually do not provide an exit status, so None is expected.

Expect

For prompt-based automation, use ExpectSession directly:

from maxconn.automation import ExpectSession, PromptProfile

expect = ExpectSession(conn, prompt_markers=PromptProfile.CISCO)
output = expect.run("show running-config", timeout=20.0)

ExpectSession handles the common parts of a network device CLI:

  • waits for prompts
  • strips command echo
  • answers simple pagination markers such as --More--
  • includes partial output in timeout errors

Timeouts

connect() accepts separate timeouts:

conn = maxconn.connect(
    "192.0.2.30",
    protocol="ssh",
    username="admin",
    password="secret",
    connect_timeout=5.0,
    auth_timeout=10.0,
    command_timeout=5.0,
    prompt_timeout=10.0,
)

The older timeout= argument still works. When connect_timeout or auth_timeout is not provided, timeout= is used as the default.

Logging

Command execution writes audit events through the maxconn.audit logger:

import logging

logging.basicConfig(level=logging.INFO)

Command fragments with words such as password, secret, token, or key are redacted before logging.

Errors

Use the project exception hierarchy:

import maxconn

try:
    with maxconn.connect(
        "192.0.2.30",
        protocol="ssh",
        username="admin",
        password="bad-password",
    ) as conn:
        print(conn.run("show status", prompt_markers=(">", "#")).text)
except maxconn.AuthenticationError:
    print("Login failed")
except maxconn.ConnectionTimeoutError:
    print("Connection timed out")
except maxconn.ProtocolError as exc:
    print(f"Protocol problem: {exc}")
except maxconn.MaxConnError as exc:
    print(f"maxconn error: {exc}")

Project Direction

  • Do not turn the project into a wrapper around Paramiko, Netmiko, Scrapli, or Telnetlib.
  • Keep optional dependencies behind extras.
  • Keep raw bytes available for code that needs them.
  • Keep the common API simple.
  • Test against local Telnet and SSH servers when it makes sense.

Download files

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

Source Distribution

maxconn-0.1.0.tar.gz (30.6 kB view details)

Uploaded Source

Built Distribution

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

maxconn-0.1.0-py3-none-any.whl (27.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: maxconn-0.1.0.tar.gz
  • Upload date:
  • Size: 30.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for maxconn-0.1.0.tar.gz
Algorithm Hash digest
SHA256 34e0d85a830b36c23818c440f7f983f815148d4ece01f329a6eb07c10ed63955
MD5 c492801c64e8ad6cf67ef181fe2cf3f3
BLAKE2b-256 2a6a58028ae616746d60419f7d507fbb05bfaf3f3edc6cf7f668b54c00302d8f

See more details on using hashes here.

Provenance

The following attestation bundles were made for maxconn-0.1.0.tar.gz:

Publisher: publish.yml on mmaxjr/maxconn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

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

File metadata

  • Download URL: maxconn-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 27.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for maxconn-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2d7f8f2e3cc5b5acc2c8aceaf33d30a82857a10a4493f5187e0f810c2892b250
MD5 18b7ade1baf0326fd657717332030049
BLAKE2b-256 9f843189f000ce6c82e09003eefed71236e4ca662762e1bbda1970cc1052cdf5

See more details on using hashes here.

Provenance

The following attestation bundles were made for maxconn-0.1.0-py3-none-any.whl:

Publisher: publish.yml on mmaxjr/maxconn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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