vnc截屏代码,传输前进行了压缩,不是RAW格式
# -*- coding: utf-8 -*-
"""
VNC 定时截屏脚本(ZRLE 编码 + 长期监控版)
- 编码: 优先 ZRLE(zlib+游程),RAW 仅作兜底 —— 1920x1080 每帧从 ~8.3MB 降至几百 KB
(vncdotool 1.4.2 无 Tight 解码器,JPEG 质量档暂不可用;上游发布后升级即可)
- 每张截图: 新建连接 -> 截屏 -> 主动断开
- 服务端/VPN 掉线时不退出,指数退避循环等待恢复
- Ctrl+C 干净退出
"""
import sys
import time
import socket
import logging
from datetime import datetime
from pathlib import Path
from PIL import Image, ImageStat
import vncdotool
from vncdotool import api
from vncdotool.client import VNCDoToolClient, VNCDoToolFactory
from vncdotool.rfb import Encoding
# ---------- 调试日志 ----------
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
handlers=[
logging.FileHandler("vnc_shoot.log", encoding="utf-8"),
logging.StreamHandler(sys.stdout),
],
)
log = logging.getLogger("vnc_shoot")
print(f"vncdotool version: {vncdotool.__version__}", flush=True)
# ---------- 配置 ----------
SAVE_DIR = Path(r"vnc_shots")
SERVER = "10.8.0.18::5900" # 双冒号 = 端口号;单冒号会被当作 display 号
PASSWORD = "xtgl" # 建议用 UltraVNC 的查看密码
INTERVAL = 30 # 正常截屏间隔(秒)
RETRY_INIT = 10 # 掉线后首次重试等待(秒)
RETRY_MAX = 300 # 重试等待上限(秒),指数退避封顶
PROBE_TIMEOUT = 5 # TCP 端口探测超时(秒)
class ZrleClient(VNCDoToolClient):
"""优先使用 ZRLE 编码;服务端不支持时自动回退 RAW"""
encoding = Encoding.ZRLE
class ZrleFactory(VNCDoToolFactory):
protocol = ZrleClient
class BlankScreenError(RuntimeError):
pass
def parse_server(server):
"""'host::port' -> (host, port);'host:N' 按 display 号解析为 5900+N"""
if "::" in server:
host, port = server.rsplit("::", 1)
return host, int(port)
host, disp = server.rsplit(":", 1)
return host, 5900 + int(disp)
HOST, PORT = parse_server(SERVER)
def is_blank_image(path, threshold=5):
"""整帧像素几乎一致(纯黑/纯色)时判定为无效截图"""
with Image.open(path).convert("RGB") as im:
st = ImageStat.Stat(im)
return max(st.mean) < threshold and max(st.stddev) < threshold
def server_reachable():
"""短超时 TCP 探测,避免每次白等 vncdotool 的 30 秒超时"""
try:
with socket.create_connection((HOST, PORT), timeout=PROBE_TIMEOUT):
return True
except OSError:
return False
def capture_once():
"""连接 -> 截屏 -> 断开(with 退出时自动 disconnect)"""
fname = datetime.now().strftime("shot_%Y%m%d_%H%M%S.png")
path = SAVE_DIR / fname
with api.connect(SERVER, password=PASSWORD, timeout=30,
factory_class=ZrleFactory) as client:
client.captureScreen(str(path)) # 全量截屏
if not path.exists() or path.stat().st_size == 0:
raise RuntimeError(f"截图文件无效: {path}")
return path
def main():
fail = 0 # 连续失败次数
down_since = None # 掉线起始时间,用于累计离线时长
log.info("server = %s, save dir = %s, interval = %ss, encoding = ZRLE",
SERVER, SAVE_DIR.resolve(), INTERVAL)
while True:
# ---- 掉线期间的等待循环:不退出,直到服务端恢复 ----
if fail > 0:
wait = min(RETRY_INIT * (2 ** (fail - 1)), RETRY_MAX)
if down_since is None:
down_since = time.time()
offline = int(time.time() - down_since)
log.warning("服务端不可达/截图失败已连续 %d 次(已离线约 %d 秒),"
"%d 秒后重试...", fail, offline, wait)
time.sleep(wait)
if not server_reachable():
fail += 1
continue
log.info("端口探测通过,服务端已恢复,尝试截屏...")
# ---- 正常截屏 ----
try:
path = capture_once()
if is_blank_image(path):
raise BlankScreenError(f"{path} ({path.stat().st_size} bytes)")
fail = 0
if down_since is not None:
log.info("服务端恢复,累计离线约 %d 秒", int(time.time() - down_since))
down_since = None
log.info("saved: %s (%d bytes)", path, path.stat().st_size)
time.sleep(INTERVAL)
except BlankScreenError as e:
fail += 1
log.warning("第 %d 次异常: 黑屏截图 %s", fail, e)
except Exception as e:
fail += 1
log.warning("第 %d 次截图失败: %s: %s", fail, type(e).__name__, e)
if __name__ == "__main__":
SAVE_DIR.mkdir(parents=True, exist_ok=True)
try:
main()
except KeyboardInterrupt:
log.info("收到 Ctrl+C,退出")
finally:
api.shutdown() # 干净地停掉后台 reactor 线程
# -*- coding: utf-8 -*- """ VNC 定时截屏脚本(ZRLE 编码 + 长期监控版) - 编码: 优先 ZRLE(zlib+游程),RAW 仅作兜底 —— 1920x1080 每帧从 ~8.3MB 降至几百 KB (vncdotool 1.4.2 无 Tight 解码器,JPEG 质量档暂不可用;上游发布后升级即可) - 每张截图: 新建连接 -> 截屏 -> 主动断开 - 服务端/VPN 掉线时不退出,指数退避循环等待恢复 - Ctrl+C 干净退出 """ import sys import time import socket import logging from datetime import datetime from pathlib import Path from PIL import Image, ImageStat import vncdotool from vncdotool import api from vncdotool.client import VNCDoToolClient, VNCDoToolFactory from vncdotool.rfb import Encoding # ---------- 调试日志 ---------- logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", handlers=[ logging.FileHandler("vnc_shoot.log", encoding="utf-8"), logging.StreamHandler(sys.stdout), ], ) log = logging.getLogger("vnc_shoot") print(f"vncdotool version: {vncdotool.__version__}", flush=True) # ---------- 配置 ---------- SAVE_DIR = Path(r"vnc_shots") SERVER = "10.8.0.18::5900" # 双冒号 = 端口号;单冒号会被当作 display 号 PASSWORD = "xtgl" # 建议用 UltraVNC 的查看密码 INTERVAL = 30 # 正常截屏间隔(秒) RETRY_INIT = 10 # 掉线后首次重试等待(秒) RETRY_MAX = 300 # 重试等待上限(秒),指数退避封顶 PROBE_TIMEOUT = 5 # TCP 端口探测超时(秒) class ZrleClient(VNCDoToolClient): """优先使用 ZRLE 编码;服务端不支持时自动回退 RAW""" encoding = Encoding.ZRLE class ZrleFactory(VNCDoToolFactory): protocol = ZrleClient class BlankScreenError(RuntimeError): pass def parse_server(server): """'host::port' -> (host, port);'host:N' 按 display 号解析为 5900+N""" if "::" in server: host, port = server.rsplit("::", 1) return host, int(port) host, disp = server.rsplit(":", 1) return host, 5900 + int(disp) HOST, PORT = parse_server(SERVER) def is_blank_image(path, threshold=5): """整帧像素几乎一致(纯黑/纯色)时判定为无效截图""" with Image.open(path).convert("RGB") as im: st = ImageStat.Stat(im) return max(st.mean) < threshold and max(st.stddev) < threshold def server_reachable(): """短超时 TCP 探测,避免每次白等 vncdotool 的 30 秒超时""" try: with socket.create_connection((HOST, PORT), timeout=PROBE_TIMEOUT): return True except OSError: return False def capture_once(): """连接 -> 截屏 -> 断开(with 退出时自动 disconnect)""" fname = datetime.now().strftime("shot_%Y%m%d_%H%M%S.png") path = SAVE_DIR / fname with api.connect(SERVER, password=PASSWORD, timeout=30, factory_class=ZrleFactory) as client: client.captureScreen(str(path)) # 全量截屏 if not path.exists() or path.stat().st_size == 0: raise RuntimeError(f"截图文件无效: {path}") return path def main(): fail = 0 # 连续失败次数 down_since = None # 掉线起始时间,用于累计离线时长 log.info("server = %s, save dir = %s, interval = %ss, encoding = ZRLE", SERVER, SAVE_DIR.resolve(), INTERVAL) while True: # ---- 掉线期间的等待循环:不退出,直到服务端恢复 ---- if fail > 0: wait = min(RETRY_INIT * (2 ** (fail - 1)), RETRY_MAX) if down_since is None: down_since = time.time() offline = int(time.time() - down_since) log.warning("服务端不可达/截图失败已连续 %d 次(已离线约 %d 秒)," "%d 秒后重试...", fail, offline, wait) time.sleep(wait) if not server_reachable(): fail += 1 continue log.info("端口探测通过,服务端已恢复,尝试截屏...") # ---- 正常截屏 ---- try: path = capture_once() if is_blank_image(path): raise BlankScreenError(f"{path} ({path.stat().st_size} bytes)") fail = 0 if down_since is not None: log.info("服务端恢复,累计离线约 %d 秒", int(time.time() - down_since)) down_since = None log.info("saved: %s (%d bytes)", path, path.stat().st_size) time.sleep(INTERVAL) except BlankScreenError as e: fail += 1 log.warning("第 %d 次异常: 黑屏截图 %s", fail, e) except Exception as e: fail += 1 log.warning("第 %d 次截图失败: %s: %s", fail, type(e).__name__, e) if __name__ == "__main__": SAVE_DIR.mkdir(parents=True, exist_ok=True) try: main() except KeyboardInterrupt: log.info("收到 Ctrl+C,退出") finally: api.shutdown() # 干净地停掉后台 reactor 线程
浙公网安备 33010602011771号