Metadata-Version: 2.4
Name: portpulse-cli
Version: 0.1.0
Summary: Zero-dependency Linux listening-port inventory, process attribution and baseline drift checks
Author-email: StackPulse Lab <360556499+stackpulse-lab@users.noreply.github.com>
License: MIT
Project-URL: Homepage, https://github.com/stackpulse-lab/portpulse
Project-URL: Issues, https://github.com/stackpulse-lab/portpulse/issues
Project-URL: Source, https://github.com/stackpulse-lab/portpulse
Keywords: ports,netstat,ss,procfs,devops,troubleshooting,cli,baseline
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: System :: Systems Administration
Classifier: Topic :: System :: Networking
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# PortPulse · 端口脉冲

[![CI](https://github.com/stackpulse-lab/portpulse/actions/workflows/ci.yml/badge.svg)](https://github.com/stackpulse-lab/portpulse/actions/workflows/ci.yml)
![PyPI](https://img.shields.io/badge/pypi-portpulse--cli-blue)
![Python](https://img.shields.io/badge/python-3.9%2B-blue)
![License](https://img.shields.io/badge/license-MIT-green)

**零依赖的 Linux 监听端口清单、进程归因与端口基线漂移检查。**

排查「这个端口被谁占了」通常是一串 `ss`、`lsof`、`ps` 拼起来的目测；而「昨天还好好的，今天多了一个监听」往往要等出事才发现。PortPulse 把这两件事变成一条可进 CI 的命令：列出监听端口，并把当前状态与基线清单对账，输出 `missing` / `unexpected` / `changed` / `conflict`，用退出码表达结论。

> 状态：`v0.1.0` 本地完成（55 个标准库测试 + 真机验证）。GitHub 仓库与 PyPI 发布需管理员创建仓库并配置 OIDC 后执行；PyPI 项目名计划为 `portpulse-cli`，命令名为 `portpulse`。

---

## 为什么不是又一个 `ss` 包装

`ss` 是查看工具，PortPulse 是对账工具：

| 场景 | `ss` / `netstat` | PortPulse |
| --- | --- | --- |
| 这个端口是谁 | ✅ 更快 | ✅ 表格 + 稳定 JSON |
| 端口清单是否漂移 | ❌ 自己 diff | ✅ `baseline` + `check`，退出码 4 |
| 同端口重复绑定 / 通配重叠 | ❌ 肉眼比对 | ✅ `conflict` 自动识别 |
| 进 CI / 定时巡检 | 解析文本，格式随版本变 | ✅ 稳定 JSON schema、零依赖 |
| 读取权限 | 部分字段需 root | ✅ 降级：未归因明确计数，不报错 |

PortPulse 只读 `/proc`，不发起网络连接、不杀进程、不改系统配置。

## 安装

```bash
# 源码安装（当前可用；仓库创建后同样适用）
git clone https://github.com/stackpulse-lab/portpulse.git
cd portpulse
python3 -m pip install .

# 首次 PyPI 发布后：
pip install portpulse-cli
# 或用 pipx 隔离安装：
pipx install portpulse-cli
```

要求：Linux（依赖 procfs）、Python 3.9+、无第三方依赖。

## 快速开始

### 1. 列出现有监听端口

```bash
$ portpulse list
PROTO  ADDRESS    PORT   STATE   PID      PROCESS       USER        CMD
-----  ---------  -----  ------  -------  ------------  ----------  -----------------------------
udp    127.0.0.1  323    UNCONN  -        -             -           -
tcp    ::         9090   LISTEN  -        -             -           -
tcp    0.0.0.0    22223  LISTEN  -        -             -           -
tcp    127.0.0.1  43843  LISTEN  2045626  opencode.exe  stackpulse  /usr/local/lib/.../opencode.exe serve --stdio
7 sockets (tcp=5 udp=2); unattributed=6 (run as root for full attribution)
```

以普通用户运行时，内核会隐藏其他用户的 `/proc/<pid>/fd`，因此部分 socket 显示 `-`；工具会统计 `unattributed` 并在摘要提示，不会把「看不到」伪装成「没有进程」。需要完整归因时用 `sudo` 或具备 `CAP_SYS_PTRACE` 的账号。

```bash
portpulse list --json                 # 机器可读（稳定字段）
portpulse list --proto tcp --port 443 # 过滤协议 / 端口（--port 可重复）
portpulse list --process nginx        # 按进程名或命令行过滤
portpulse list --all                  # 包含 ESTABLISHED 等非监听 socket
```

### 2. 建立端口基线并检查漂移

```bash
# 记录「这台机器应该监听什么」
portpulse baseline --write ports-baseline.json

# 日常巡检 / CI：与基线对账
portpulse check --baseline ports-baseline.json
```

真实输出（本机验证，启动一个临时 HTTP 服务后）：

```text
$ portpulse check --baseline ports-baseline.json
drift detected: 7 expected / 8 current socket(s)
unexpected: tcp 127.0.0.1:18731 process=python3 user=stackpulse
$ echo $?
4

$ kill <pid>   # 关掉临时服务后
$ portpulse check --baseline ports-baseline.json
baseline matches: 7 expected / 7 current socket(s)
$ echo $?
0
```

`check` 的四类结果：

- `missing`：基线里有、现在没有（服务没起来 / 被误停）；
- `unexpected`：基线里没有、现在多了（新后门、误开的调试端口、容器端口映射）；
- `changed`：端口还在，但持有进程或用户变了（被其他程序抢占）；
- `conflict`：同一 `proto + port` 出现重复地址绑定，或 `0.0.0.0` / `::` 与具体地址重叠（绑定顺序决定谁生效，是典型事故源）。

### 3. JSON 巡检脚本示例

```bash
portpulse check --baseline ports-baseline.json --json > drift.json || status=$?
python3 - <<'PY'
import json
report = json.load(open("drift.json"))
if not report["ok"]:
    print("drift:", report["counts"])
    for item in report["unexpected"]:
        print("new listener:", item["port"], item["process"])
PY
```

## 退出码

| 退出码 | 含义 |
| --- | --- |
| `0` | 无漂移、无冲突（或命令成功） |
| `2` | 参数错误 / 基线不可读或格式非法 / procfs 不可读 |
| `4` | 检测到漂移或端口冲突（`check` 专用） |

`--json` 与文本输出同源，退出码语义一致；脚本请使用退出码，而不是 grep 文本。

## 基线清单格式

```json
{
  "version": 1,
  "host": "web-01",
  "generated_at": "2026-11-29T06:01:49+08:00",
  "ports": [
    { "proto": "tcp", "address": "0.0.0.0", "port": 22, "process": "sshd", "user": "root" }
  ]
}
```

- 身份键是 `proto + address + port`；`process` / `user` 用于判断 `changed`。
- 基线不包含任何连接内容、环境变量或凭据，可以安全提交到内部仓库评审。
- 若基线中的进程或用户未知（`-`），`check` 不会因此误报 `changed`——先补齐归因再收紧基线。

## 工作方式与边界

- 数据来源：`/proc/net/{tcp,tcp6,udp,udp6}` + `/proc/<pid>/fd` 的 `socket:[inode]` 反查；UID 经 `/proc/<pid>/status` 解析。
- UDP 没有 `LISTEN` 状态，未连接且已绑定的 UDP socket 以 `UNCONN` 展示（与 `ss` 一致）。
- `--proc-root` 可指向任意 procfs 快照或测试夹具，便于在容器/离线样本中复现。
- 已知边界：只覆盖当前网络命名空间；`*.timer.d` 式的外部编排不在范围内；不解析 eBPF、不追踪短连接；容器内看到的是容器命名空间。
- 归因是尽力而为：权限不足时返回 `-` 并计入 `unattributed`，不会猜测 PID。

## 开发

```bash
python3 run_tests.py     # 55 个测试，纯标准库
PYTHONPATH=src python3 -m portpulse list
```

测试使用真实格式的 `/proc/net/*` 夹具与伪造 `fd` 符号链接，不依赖宿主端口状态；CI 覆盖 Python 3.9–3.13 与 wheel/sdist 构建。

## License

MIT © 2026 StackPulse Lab

---

# PortPulse (English)

**Zero-dependency Linux listening-port inventory, process attribution and baseline drift checks.**

`ss` answers "what is on this port right now". PortPulse answers "is this host still listening on exactly what we expect" — with a stable JSON schema and an exit code you can put in CI.

> Status: `v0.1.0` is complete locally (55 stdlib tests + real-host verification). The GitHub repository and PyPI release require an administrator to create the repo and configure OIDC. Planned distribution name: `portpulse-cli`; command: `portpulse`.

## Install

```bash
git clone https://github.com/stackpulse-lab/portpulse.git
cd portpulse && python3 -m pip install .

# after the first PyPI release
pip install portpulse-cli
```

Requires Linux (procfs) and Python 3.9+. No third-party dependencies.

## Usage

```bash
portpulse list                         # listening sockets, table
portpulse list --json                  # stable machine-readable output
portpulse list --proto tcp --port 443  # filter (repeatable --port)
portpulse list --process nginx         # filter by process / cmdline
portpulse list --all                   # include non-listening sockets

portpulse baseline --write ports-baseline.json
portpulse check --baseline ports-baseline.json
```

`check` reports `missing`, `unexpected`, `changed` (owner changed) and `conflict` (duplicate or wildcard/specific overlap on the same proto+port), and exits `4` on any drift. Exit `2` means bad input or unreadable procfs; `0` means the host matches the baseline.

Verified on a live host: adding a temporary `python3 -m http.server 18731` produced

```text
drift detected: 7 expected / 8 current socket(s)
unexpected: tcp 127.0.0.1:18731 process=python3 user=stackpulse
exit=4
```

and returned to `baseline matches: 7 expected / 7 current socket(s)` / exit `0` after the listener was stopped.

## Notes and limits

- Reads `/proc/net/{tcp,tcp6,udp,udp6}` and resolves inodes via `/proc/<pid>/fd`; read-only, no connections, no process signals.
- Attribution is best effort. Without privileges the kernel hides other users' FDs, so sockets show `-` and are counted as `unattributed`; run with `sudo` for full attribution.
- UDP bound-but-unconnected sockets are shown as `UNCONN` (same as `ss`).
- Only the current network namespace is visible; short-lived connections and eBPF data are out of scope.
- `--proc-root` points at any procfs snapshot or test fixture.

## Development

```bash
python3 run_tests.py   # 55 tests, stdlib only
```

MIT © 2026 StackPulse Lab
