DatacomShell
面向网络设备的 Python 远程管理工具库,统一封装 SSH 与 Telnet 协议交互。
功能特性
- SSH 客户端 (
SyncSSHClientUtil) — 基于paramiko,使用交互式 shell 适配网络设备(交换机/路由器等) - Telnet 客户端 (
AsyncTelnetClientUtil) — 基于telnetlib3,异步底层,对外暴露统一同步接口 - 统一抽象接口 (
AbsClient) — 两种协议使用完全一致的方法调用风格 - Builder 参数构建 — 所有配置项通过链式 Builder 构建,清晰可维护
- 会话日志记录 — 自动按时间窗口切分日志文件,支持
[start]/[end]标记 - 多种认证方式 — 支持无认证、用户名/密码认证
安装
本项目使用 uv 作为包管理器。
# 克隆仓库
git clone <repository-url>
cd DatacomShell
# 安装依赖
uv sync
# 激活虚拟环境(Windows)
.venv\Scripts\activate
快速开始
SSH 连接示例
from datacomshell.SyncSSHClientUtil import SyncSSHClientUtil, SyncSSHClientParam
param = SyncSSHClientParam.builder()\
.set_host('192.168.1.1')\
.set_port(22)\
.set_username('admin')\
.set_password('Admin@123')\
.set_timeout(15.0)\
.set_log_folder_path('./ssh_logs')\
.build()
client = SyncSSHClientUtil(param)
try:
client.connect()
result = client.execute('display version')
print(result)
finally:
client.close()
Telnet 连接示例
from datacomshell.AsyncTelnetClientUtil import AsyncTelnetClientUtil, AsyncTelnetClientParam
from datacomshell.Auth import UsernamePasswordAuth
auth = UsernamePasswordAuth('admin', 'Admin@123')
param = AsyncTelnetClientParam.builder()\
.set_host('192.168.1.1')\
.set_port(23)\
.set_auth(auth)\
.set_connect_timeout(10.0)\
.set_login_timeout(10.0)\
.set_command_timeout(15.0)\
.set_log_folder_path('./telnet_logs')\
.build()
client = AsyncTelnetClientUtil(param)
try:
client.connect()
result = client.execute('display version')
print(result)
finally:
client.close()
统一接口 — 批量管理多设备
from datacomshell.abs_client import AbsClient
def run_on_device(client: AbsClient, device_name: str):
try:
client.connect()
result = client.execute('display version')
print(f"[{device_name}] 执行成功")
return result
except Exception as e:
print(f"[{device_name}] 执行失败: {e}")
finally:
client.close()
# SSH 设备
ssh_param = SyncSSHClientParam.builder()\
.set_host('10.0.0.1').set_username('admin').set_password('Admin@123').build()
run_on_device(SyncSSHClientUtil(ssh_param), 'SSH-Switch-01')
# Telnet 设备
auth = UsernamePasswordAuth('admin', 'Admin@123')
telnet_param = AsyncTelnetClientParam.builder()\
.set_host('10.0.0.2').set_auth(auth).build()
run_on_device(AsyncTelnetClientUtil(telnet_param), 'Telnet-Switch-01')
项目架构
┌─────────────────────────────────────────────┐
│ 应用层 (App Layer) │
│ 运维脚本 / CLI 入口 │
├─────────────────────────────────────────────┤
│ 抽象层 (AbsClient) │
│ connect / execute / execute_bytes / close │
├─────────────────────────────────────────────┤
│ 实现层 (Impl Layer) │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ SyncSSHClientUtil │ │AsyncTelnetClientUtil│
│ │ (paramiko) │ │ (telnetlib3) │ │
│ └──────────────────┘ └──────────────────┘ │
├─────────────────────────────────────────────┤
│ 支撑层 (Support Layer) │
│ Auth (认证) SessionLogger (日志) │
└─────────────────────────────────────────────┘
API 说明
统一接口 AbsClient
| 方法 | 签名 | 说明 |
|---|---|---|
connect |
() -> None |
建立远程连接 |
disconnect |
() -> None |
断开远程连接 |
close |
() -> None |
关闭客户端(含日志收尾) |
execute |
(command: str, timeout: float = 10.0) -> str |
执行命令,返回字符串 |
execute_bytes |
(command: str, timeout: float = 10.0) -> bytes |
执行命令,返回字节数据 |
Builder 参数链
两个客户端参数均支持链式 Builder:
SyncSSHClientParam.builder()\
.set_host(str)\
.set_port(int)\
.set_username(str)\
.set_password(str)\
.set_timeout(float)\
.set_log_folder_path(Optional[str])\
.set_log_new_second(float)\
.build()
AsyncTelnetClientParam.builder()\
.set_host(str)\
.set_port(int)\
.set_auth(Auth)\
.set_connect_timeout(float)\
.set_login_timeout(float)\
.set_command_timeout(float)\
.set_log_folder_path(Optional[str])\
.set_log_new_second(float)\
.build()
认证方式
from datacomshell.Auth import Auth, AuthState, UsernamePasswordAuth
# 无认证
no_auth = Auth()
# 用户名密码认证
user_auth = UsernamePasswordAuth('admin', 'Admin@123')
日志功能
当配置了 log_folder_path 后,客户端会自动记录每次 execute 的输入输出:
- 自动目录创建:日志目录不存在时自动创建
- 时间窗口切分:超过
log_new_second(默认 1800 秒)自动创建新日志文件 - 起止标记:每个日志文件包含
[start]和[end]时间戳标记 - 空行过滤:自动过滤纯空白行
日志示例:
================ [start]:2026-07-22_14-30-00-123456.log ================
display version
Huawei Versatile Routing Platform Software
VRP (R) software, Version 5.110 (S5700 V200R001C00)
...
================ [end]:2026-07-22_14-30-05-789012 ================
目录结构
DatacomShell/
├── src/
│ ├── datacomshell/
│ │ ├── __init__.py # 包入口
│ │ ├── abs_client.py # 抽象客户端基类
│ │ ├── Auth.py # 认证模块
│ │ ├── AsyncTelnetClientUtil.py # Telnet 客户端
│ │ ├── SyncSSHClientUtil.py # SSH 客户端
│ │ └── SessionLogger.py # 日志管理器
│ └── test/
│ ├── test.py # 交互式测试菜单
│ └── example.py # 使用示例
├── pyproject.toml # 项目配置与依赖
├── uv.lock # uv 锁定文件
└── README.md # 本文档
依赖
| 包名 | 版本 | 用途 |
|---|---|---|
paramiko |
==4.0.0 | SSHv2 协议 |
telnetlib3 |
>=4.0.2 | 异步 Telnet 协议 |
aiofiles |
>=25.1.0 | 异步文件 IO |
dataclasses |
>=0.8 | 数据类支持 |
注意事项
- 网络设备 SSH:大多数交换机/路由器不支持
exec_command,本库使用invoke_shell交互式 shell 发送命令。 - Telnet 结束标记:命令执行后会追加
[saven-process-end]标记,通过匹配该标记确认命令执行完成。 - 超时处理:Telnet 的
login_timeout控制认证阶段超时,command_timeout控制命令执行超时。
作者
Saven — 2416844857@qq.com
License
MIT License
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
datacomshell-0.26.10.tar.gz
(8.0 kB
view details)
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 datacomshell-0.26.10.tar.gz.
File metadata
- Download URL: datacomshell-0.26.10.tar.gz
- Upload date:
- Size: 8.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
da4859a824318d01984f0ff65d739c7bfe9fa861582f73e5697910c1b0ddd45d
|
|
| MD5 |
8bf3d5187f46a89a1333aed875a5d130
|
|
| BLAKE2b-256 |
c220d32de0ed033f43e96ba46c63225de96ff7a9ce4cebbc2002980c290d7ab1
|
File details
Details for the file datacomshell-0.26.10-py3-none-any.whl.
File metadata
- Download URL: datacomshell-0.26.10-py3-none-any.whl
- Upload date:
- Size: 11.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ebaf9a53915fc4dd013d82f1cc29e6b8973dbde96109a82b69dec876c4d1eed3
|
|
| MD5 |
75a7e41c79f71959be16071f322c88d8
|
|
| BLAKE2b-256 |
1ee38a099f362fbda0bb1cd5fe145c58f493260a8da17c31fc01c3baaf2f70ac
|