- tools/printer_probe.py:打印机协议非破坏性探测(端口/IPP 能力/LPD 队列,绝不提交作业) - tools/printer_client.py:IPP 直连打印(info / validate 干跑 / print 需显式 --yes) - tools/doc2pdf.py:网页 / HTML / Excel 指定区域转 PDF,产物可直接交给 printer_client - tools/sheet_print.py:Excel·WPS 表格按列过滤排版后分页打印 - tools/xq0012_payapply_pdf.py:XQ0012 套打 PDF 本地预览工具 - workflows/share/erp_sso_login.py:读 OA 登录态换 ERP 会话(新版/旧版,纯接口无浏览器) - workflows/README.md 新增 4.9 节说明
388 lines
14 KiB
Python
388 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""打印机协议探测脚本(只探测,不打印)。
|
||
|
||
用途:对指定 IP 的网络打印机做非破坏性探测,逆向识别
|
||
- 开放端口(Raw9100 / IPP631 / LPD515 / HTTP80 / HTTPS443)
|
||
- 厂商与型号(HTTP Server 头、IPP Get-Printer-Attributes)
|
||
- 支持的文档格式与打印语言(application/pdf / ESC/P-R / ESC/POS ...)
|
||
- LPD 队列名(仅发送查询类命令,不提交打印作业)
|
||
本脚本不会向任何端口写入任何打印数据,可安全反复运行。
|
||
|
||
用法:
|
||
.venv\\Scripts\\python.exe tools\\printer_probe.py
|
||
.venv\\Scripts\\python.exe tools\\printer_probe.py --ip 172.30.40.254
|
||
结果同时打印到控制台并落盘 tools/printer_probe_result.json
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import socket
|
||
import struct
|
||
import sys
|
||
import time
|
||
from pathlib import Path
|
||
|
||
DEFAULT_IP = "172.30.40.254"
|
||
COMMON_PORTS = [21, 23, 80, 443, 515, 631, 9100, 8080, 8443, 161, 427, 3702, 5353]
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 基础网络工具
|
||
# --------------------------------------------------------------------------- #
|
||
def tcp_open(ip: str, port: int, timeout: float = 0.9) -> bool:
|
||
"""判断 TCP 端口是否可建立连接(不做任何读写)。"""
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
s.settimeout(timeout)
|
||
try:
|
||
return s.connect_ex((ip, port)) == 0
|
||
except OSError:
|
||
return False
|
||
finally:
|
||
s.close()
|
||
|
||
|
||
def send_recv(ip: str, port: int, payload: bytes = b"", wait: float = 0.8,
|
||
timeout: float = 4.0, first: bool = False) -> bytes:
|
||
"""建立连接、可选发送数据、读回响应。payload 为空则只做被动读取。"""
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
s.settimeout(timeout)
|
||
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||
data = b""
|
||
try:
|
||
s.connect((ip, port))
|
||
if payload:
|
||
s.sendall(payload)
|
||
time.sleep(wait)
|
||
while True:
|
||
try:
|
||
chunk = s.recv(4096)
|
||
except socket.timeout:
|
||
break
|
||
if not chunk:
|
||
break
|
||
data += chunk
|
||
if first and data:
|
||
break
|
||
if len(data) > 200_000:
|
||
break
|
||
except OSError:
|
||
pass
|
||
finally:
|
||
s.close()
|
||
return data
|
||
|
||
|
||
def dump(data: bytes, limit: int = 700) -> str:
|
||
"""把响应渲染成可读文本(不可见字节转 '.'),便于看协议头。"""
|
||
if not data:
|
||
return "<空>"
|
||
txt = data.decode("utf-8", "replace")
|
||
return "".join(c if c in "\r\n\t" or 0x20 <= ord(c) <= 0x7E else "." for c in txt)[:limit]
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# HTTP / HTTPS 探测
|
||
# --------------------------------------------------------------------------- #
|
||
HTTP_PATHS = [
|
||
"/", "/index.html", "/PRESENTATION/HTML/TOP/INDEX.HTML",
|
||
"/EPSON_HTM/HTML/TOP/INDEX.HTML", "/webconfig", "/cgi-bin/status",
|
||
"/status", "/ipp/print", "/info", "/wnstatus.cgi",
|
||
]
|
||
|
||
|
||
def http_get(ip: str, port: int, path: str, timeout: float = 4.0) -> tuple[int, str, bytes]:
|
||
"""极简 HTTP/1.0 GET(Epson 嵌入式服务器对 HTTP/1.1 会直接断链)。"""
|
||
req = (
|
||
f"GET {path} HTTP/1.0\r\n"
|
||
f"Host: {ip}:{port}\r\n"
|
||
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n"
|
||
"Accept: */*\r\n"
|
||
"Connection: close\r\n\r\n"
|
||
).encode("ascii", "ignore")
|
||
raw = send_recv(ip, port, req, wait=0.6, timeout=timeout)
|
||
if not raw:
|
||
return 0, "", b""
|
||
head = raw.split(b"\r\n\r\n", 1)[0].decode("latin-1", "replace")
|
||
first = head.split("\r\n", 1)[0]
|
||
code = 0
|
||
for tok in first.split():
|
||
if tok.isdigit():
|
||
code = int(tok)
|
||
break
|
||
body = raw.split(b"\r\n\r\n", 1)[1] if b"\r\n\r\n" in raw else b""
|
||
return code, head, body
|
||
|
||
|
||
def probe_http(ip: str, port: int) -> dict:
|
||
hits = []
|
||
for path in HTTP_PATHS:
|
||
code, head, body = http_get(ip, port, path)
|
||
if code:
|
||
hits.append({"path": path, "status": code, "headers": head, "body_len": len(body)})
|
||
print(f" {path:<38} {code} body={len(body)}B")
|
||
time.sleep(0.05)
|
||
server = ""
|
||
for h in hits:
|
||
if h["path"] == "/":
|
||
for line in h["headers"].split("\r\n"):
|
||
if line.lower().startswith("server:"):
|
||
server = line.split(":", 1)[1].strip()
|
||
return {"port": port, "server": server, "hits": hits}
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# IPP 1.1/2.0 构造(RFC 8010 / 8011)
|
||
# --------------------------------------------------------------------------- #
|
||
TAG_OPERATION = 0x01
|
||
TAG_END = 0x03
|
||
TAG_CHARSET = 0x47
|
||
TAG_LANGUAGE = 0x48
|
||
TAG_URI = 0x45
|
||
TAG_KEYWORD = 0x44
|
||
TAG_NAME = 0x42
|
||
|
||
OP_GET_PRINTER_ATTRIBUTES = 0x000B
|
||
OP_GET_JOBS = 0x000A
|
||
|
||
|
||
def _attr(tag: int, name: str, value: bytes) -> bytes:
|
||
n = name.encode("utf-8")
|
||
return bytes([tag]) + struct.pack(">H", len(n)) + n + struct.pack(">H", len(value)) + value
|
||
|
||
|
||
def ipp_request(op: int, uri: str, req_id: int = 1, extra: bytes = b"") -> bytes:
|
||
body = bytes([TAG_OPERATION])
|
||
body += _attr(TAG_CHARSET, "attributes-charset", b"utf-8")
|
||
body += _attr(TAG_LANGUAGE, "attributes-natural-language", b"en-us")
|
||
body += _attr(TAG_URI, "printer-uri", uri.encode("utf-8"))
|
||
body += extra
|
||
body += bytes([TAG_END])
|
||
return struct.pack(">BBHI", 2, 0, op, req_id) + body
|
||
|
||
|
||
def ipp_parse(data: bytes) -> tuple[int, dict]:
|
||
"""解析 IPP 响应的头两字节状态码 + 属性表(不含集合/1setOf 展开)。"""
|
||
if len(data) < 8:
|
||
return -1, {}
|
||
status = struct.unpack(">H", data[2:4])[0]
|
||
attrs: dict[str, list] = {}
|
||
i, cur = 8, None
|
||
while i < len(data):
|
||
tag = data[i]
|
||
if tag == TAG_END:
|
||
break
|
||
if tag < 0x10: # 分隔标签
|
||
i += 1
|
||
continue
|
||
if i + 2 > len(data):
|
||
break
|
||
nlen = struct.unpack(">H", data[i + 1:i + 3])[0]
|
||
name = data[i + 3:i + 3 + nlen].decode("utf-8", "replace")
|
||
i += 3 + nlen
|
||
if i + 2 > len(data):
|
||
break
|
||
vlen = struct.unpack(">H", data[i:i + 2])[0]
|
||
raw = data[i + 2:i + 2 + vlen]
|
||
i += 2 + vlen
|
||
cur = name or cur
|
||
attrs.setdefault(cur or "?", []).append((tag, raw))
|
||
return status, attrs
|
||
|
||
|
||
def _decode(tag: int, raw: bytes):
|
||
try:
|
||
if tag in (0x21, 0x23): # integer / enum
|
||
return struct.unpack(">i", raw)[0] if len(raw) == 4 else int.from_bytes(raw, "big")
|
||
if tag == 0x22:
|
||
return struct.unpack(">b", raw)[0] if len(raw) == 1 else None
|
||
if tag == 0x41: # textWithLanguage 简化
|
||
return raw.decode("utf-8", "replace")
|
||
return raw.decode("utf-8", "replace")
|
||
except Exception:
|
||
return raw.hex()
|
||
|
||
|
||
IPP_STATUS = {
|
||
0x0000: "successful-ok",
|
||
0x0400: "client-error-bad-request",
|
||
0x0401: "client-error-forbidden",
|
||
0x0403: "client-error-not-found",
|
||
0x0500: "server-error-internal-error",
|
||
0x0502: "server-error-service-unavailable",
|
||
}
|
||
|
||
|
||
def ipp_post(ip: str, port: int, path: str, body: bytes, timeout: float = 8.0,
|
||
http11: bool = True) -> tuple[int, bytes]:
|
||
"""IPP 走 HTTP POST + Content-Type: application/ipp(RFC 8010 第 4 章)。"""
|
||
ver = "HTTP/1.1" if http11 else "HTTP/1.0"
|
||
head = (
|
||
f"POST {path} {ver}\r\n"
|
||
f"Host: {ip}:{port}\r\n"
|
||
"Content-Type: application/ipp\r\n"
|
||
f"Content-Length: {len(body)}\r\n"
|
||
"Connection: close\r\n\r\n"
|
||
).encode("ascii")
|
||
raw = send_recv(ip, port, head + body, wait=1.2, timeout=timeout)
|
||
if not raw:
|
||
return 0, b""
|
||
code = 0
|
||
for tok in raw.split(b"\r\n", 1)[0].split():
|
||
if tok.isdigit():
|
||
code = int(tok)
|
||
break
|
||
resp = raw.split(b"\r\n\r\n", 1)
|
||
return code, (resp[1] if len(resp) > 1 else b"")
|
||
|
||
|
||
def probe_ipp(ip: str, port: int = 631) -> dict:
|
||
"""对 IPP 服务做 Get-Printer-Attributes,读取型号/格式/状态。"""
|
||
result: dict = {"port": port, "uri": None, "status": None, "attrs": {}}
|
||
candidates = [(f"ipp://{ip}:{port}/ipp/print", "/ipp/print"),
|
||
(f"ipp://{ip}:{port}/ipp/printer", "/ipp/printer"),
|
||
(f"ipp://{ip}:{port}/", "/"),
|
||
(f"ipp://{ip}/ipp/print", "/ipp/print")]
|
||
wanted = [b"printer-name", b"printer-info", b"printer-make-and-model",
|
||
b"printer-state", b"printer-state-reasons", b"document-format-supported",
|
||
b"document-format-default", b"compression-supported", b"ipp-versions-supported",
|
||
b"operations-supported", b"printer-location", b"printer-uuid",
|
||
b"printer-device-id", b"media-supported", b"printer-supply-info-uri",
|
||
b"sides-supported", b"output-bin-default", b"media-default",
|
||
b"print-color-mode-supported", b"printer-resolution-supported",
|
||
b"job-creation-attributes-supported", b"pdf-versions-supported",
|
||
b"document-format-preferred"]
|
||
extra = b""
|
||
payload = b""
|
||
for kw in wanted:
|
||
payload += _attr(TAG_KEYWORD, "requested-attributes", kw)
|
||
|
||
for uri, path in candidates:
|
||
req = ipp_request(OP_GET_PRINTER_ATTRIBUTES, uri, 1, payload)
|
||
code, body = ipp_post(ip, port, path, req)
|
||
status, attrs = ipp_parse(body) if len(body) >= 8 else (-1, {})
|
||
print(f" {path:<14} http={code or 'ERR':<4} ipp={IPP_STATUS.get(status, hex(status) if status >= 0 else 'none'):<26} attrs={len(attrs)}")
|
||
if attrs:
|
||
flat = {}
|
||
for k, vals in attrs.items():
|
||
flat[k] = [_decode(t, v) for t, v in vals]
|
||
result.update({"uri": uri, "path": path, "http_status": code,
|
||
"status": IPP_STATUS.get(status, hex(status)),
|
||
"attrs": flat, "raw_len": len(body)})
|
||
return result
|
||
if code:
|
||
result.update({"uri": uri, "path": path, "http_status": code,
|
||
"status": IPP_STATUS.get(status, hex(status) if status >= 0 else "none")})
|
||
time.sleep(0.05)
|
||
# / 目录下的打印机列表
|
||
root_uri = f"ipp://{ip}:{port}/"
|
||
req = ipp_request(OP_GET_PRINTER_ATTRIBUTES, root_uri, 2,
|
||
_attr(TAG_KEYWORD, "requested-attributes", b"printer-name")
|
||
+ _attr(TAG_KEYWORD, "requested-attributes", b"printer-uri-supported"))
|
||
raw = send_recv(ip, port, req, wait=1.0, timeout=6.0)
|
||
if len(raw) >= 8:
|
||
st, at = ipp_parse(raw)
|
||
if at:
|
||
result["root_uri"] = root_uri
|
||
result["root_attrs"] = {k: [_decode(t, v) for t, v in vv] for k, vv in at.items()}
|
||
return result
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# LPD (RFC 1179) 队列探测:只发查询,不发打印
|
||
# --------------------------------------------------------------------------- #
|
||
LPD_QUEUES = ["PASSTHRU", "EPSON", "PRINT", "lp", "LPT1", "RAW", "TEXT", "BINARY_P1", "auto"]
|
||
|
||
|
||
def probe_lpd(ip: str, port: int = 515) -> dict:
|
||
"""发送 LPD 状态查询命令(\\x04queue\\n),返回队列是否存在。
|
||
|
||
注意:\\x04 是 "查询队列状态",不是打印命令;本函数不会发送 \\x02 作业提交。
|
||
"""
|
||
out = {}
|
||
for q in LPD_QUEUES:
|
||
req = b"\x04" + q.encode() + b"\n"
|
||
raw = send_recv(ip, port, req, wait=0.6, timeout=3.0)
|
||
state = "no-reply"
|
||
if raw:
|
||
state = dump(raw, 160).replace("\r", "\\r").replace("\n", "\\n")
|
||
out[q] = state
|
||
print(f" queue {q:<12} -> {state[:90]}")
|
||
time.sleep(0.05)
|
||
return {"port": port, "queues": out}
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 9100 Raw 探测:只发送 PJL 状态命令(UEL + INFO),绝不发送打印数据
|
||
# --------------------------------------------------------------------------- #
|
||
PJL_INFO = (
|
||
b"\x1b%-12345X@PJL\r\n"
|
||
b"@PJL INFO ID\r\n"
|
||
b"@PJL INFO STATUS\r\n"
|
||
b"@PJL INFO CONFIG\r\n"
|
||
b"@PJL USTATUS DEVICE = ON\r\n"
|
||
b"\x1b%-12345X"
|
||
)
|
||
|
||
|
||
def probe_raw(ip: str, port: int = 9100) -> dict:
|
||
"""9100 端口 PJL 探测。EPSON 喷墨多数不实现 PJL,会静默或回显。"""
|
||
raw = send_recv(ip, port, PJL_INFO, wait=1.2, timeout=4.0)
|
||
print(f" PJL INFO -> {len(raw)}B {dump(raw, 240)}")
|
||
|
||
# Epson 远程状态查询:ESC/P 的 "ESC ( U" 等需要真实打印通道,此处不发送。
|
||
# 仅做连通性与静默性判定:连接成功但不回数据,说明为纯打印数据通道。
|
||
return {"port": port, "pjl_bytes": len(raw), "pjl_reply": dump(raw, 600),
|
||
"pure_data_channel": len(raw) == 0}
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 主流程
|
||
# --------------------------------------------------------------------------- #
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--ip", default=DEFAULT_IP)
|
||
ap.add_argument("--out", default="tools/printer_probe_result.json")
|
||
args = ap.parse_args()
|
||
ip = args.ip
|
||
|
||
report: dict = {"ip": ip, "time": time.strftime("%Y-%m-%d %H:%M:%S"), "ports": {}}
|
||
|
||
print(f"[1/5] 端口扫描 {ip}")
|
||
for p in COMMON_PORTS:
|
||
open_ = tcp_open(ip, p)
|
||
report["ports"][p] = open_
|
||
if open_:
|
||
print(f" {p:<6} OPEN")
|
||
|
||
if report["ports"].get(80):
|
||
print("[2/5] HTTP 探测 :80")
|
||
report["http80"] = probe_http(ip, 80)
|
||
if report["ports"].get(443):
|
||
print("[2/5] HTTPS 探测 :443")
|
||
report["https443"] = {"note": "443 开放;嵌入式 Epson 多为自签证书,"
|
||
"本次仅记录端口,未做 TLS 握手(避免证书告警)"}
|
||
|
||
if report["ports"].get(631):
|
||
print("[3/5] IPP Get-Printer-Attributes :631")
|
||
report["ipp"] = probe_ipp(ip, 631)
|
||
|
||
if report["ports"].get(515):
|
||
print("[4/5] LPD 队列查询 :515")
|
||
report["lpd"] = probe_lpd(ip, 515)
|
||
|
||
if report["ports"].get(9100):
|
||
print("[5/5] Raw 9100 PJL 探测")
|
||
report["raw9100"] = probe_raw(ip, 9100)
|
||
|
||
out = Path(args.out)
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
out.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
print(f"\n结果已写入 {out.resolve()}")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|