Syncthing 2.1.7 常用 CLI 命令与工具详解

Syncthing 2.1.7 命令行全家桶实测:主命令树与 serve 全参数、syncthing cli 三大子命令组、generate/paths/device-id/debug 辅助命令、strelaysrv/stdiscosrv 服务端工具,以及 REST API 认证与常用端点 curl 实测。

Syncthing备份恢复2026/10/22

Syncthing 2.1.7 常用 CLI 命令与工具详解

目标:逐一给可执行的命令与真实回显——覆盖 syncthing 主命令树、serve 全参数、cli 三大子命令组、辅助命令与服务端工具,最后落到 REST API 的认证与常用端点。全部输出在 Ubuntu 22.04.5 + Syncthing v2.1.7 实测照抄。

一、环境信息

  • 操作系统:Ubuntu 22.04.5 LTS(x86_64,systemd 249)
  • Syncthing:v2.1.7 "Hafnium Hornet"(官方 deb 安装,/usr/bin/syncthing)
  • 运行方式:systemd 模板服务 syncthing@root(安装过程见 《Ubuntu 22.04 安装 Syncthing 指南》)
  • API 凭据:REST 调用使用本机 config.xml 实测 API Key LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL(读者应取自己设备 config.xml 中的 <apikey> 值)
  • 服务端工具:syncthing-relaysrv 2.1.7、syncthing-discosrv 2.1.7(独立 deb 包,/usr/bin/strelaysrv、/usr/bin/stdiscosrv)

二、工具概览

Syncthing v2 的命令面分三层(v2.1.7 实测):

层入口用途
主命令syncthing <command>进程运行(serve)与一次性工具(generate/paths/device-id 等)
管理 CLIsyncthing cli <group> <cmd>面向运行中实例的查询与操作(封装 REST API)
REST APIcurl http://127.0.0.1:8384/rest/...全功能编程接口(CLI 与 Web GUI 的底层)
服务端工具strelaysrv / stdiscosrv自建中继服务器 / 自建全局发现服务器(v2 独立 deb 包)

💡 技术拓展:v1→v2 命令面最大变化——v1 把全部运行参数放在主命令(syncthing --gui-address=... 等),v2 收敛为子命令树:运行参数全部移入 syncthing serve,新增 decrypt(解密加密文件夹)等子命令。老脚本迁移时先看第二章的命令树。

三、前置条件

  1. Syncthing 已安装并可运行:
syncthing --version

实测回显:

syncthing v2.1.7 "Hafnium Hornet" (go1.27.3 linux-amd64) debian@github.syncthing.net 2026-10-20 19:54:38 UTC [noupgrade]
  1. 实例以服务运行、GUI/API 已监听(CLI 与 REST 都依赖它):
systemctl is-active syncthing@root && curl -s -H "X-API-Key: LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL" http://127.0.0.1:8384/rest/system/ping

实测回显:

active
{
  "ping": "pong"
}

四、主命令与 serve 参数详解

4.1 主命令树

syncthing --help

实测回显(全文):

Usage: syncthing <command> [flags]

Flags:
  -h, --help           Show context-sensitive help.
  -C, --config=PATH    Set configuration directory (config and keys)
                       ($STCONFDIR)
  -D, --data=PATH      Set data directory (database and logs) ($STDATADIR)
  -H, --home=PATH      Set configuration and data directory ($STHOMEDIR)
      --version        Show current version, then exit

Commands:
  serve                  Run Syncthing (default)
  cli                    Command line interface for Syncthing
  browser                Open GUI in browser, then exit
  decrypt                Decrypt or verify an encrypted folder
  device-id              Show device ID, then exit
  generate               Generate key and config, then exit
  paths                  Show configuration paths, then exit
  upgrade                Perform or check for upgrade, then exit
  version                Show current version, then exit
  debug                  Various debugging commands
  install-completions    Print commands to install shell completions

Run "syncthing <command> --help" for more information on a command.

解读:全局 flag 只有四个路径项(-C/-D/-H 与 --version)——v2 把运行参数全部收进 serve 子命令;serve 是缺省命令(裸跑 syncthing 等价 syncthing serve)。各子命令一句话用途:

子命令用途详见
serve运行同步守护进程(服务模式核心)4.2
cli管理运行中实例第五章
browser打开 GUI 浏览器后退出(桌面用)—
decrypt解密/校验 receiveencrypted 文件夹6.3
device-id打印本机设备 ID6.2
generate生成密钥与配置(GUI 账号重置)6.1
paths打印配置/数据目录布局6.4
upgrade / version升级检查 / 版本信息6.5
debug数据库维护调试6.6
install-completions输出 shell 补全安装命令—

4.2 serve:运行参数全解

syncthing serve --help

实测回显(全文):

Usage: syncthing serve [flags]

Run Syncthing (default)

Flags:
  -h, --help                      Show context-sensitive help.
  -C, --config=PATH               Set configuration directory (config and keys)
                                  ($STCONFDIR)
  -D, --data=PATH                 Set data directory (database and logs)
                                  ($STDATADIR)
  -H, --home=PATH                 Set configuration and data directory
                                  ($STHOMEDIR)
      --version                   Show current version, then exit

      --allow-newer-config        Allow loading newer than current config
                                  version ($STALLOWNEWERCONFIG)
      --audit                     Write events to audit file ($STAUDIT)
      --auditfile=PATH            Specify audit file (use "-" for stdout,
                                  "--" for stderr) ($STAUDITFILE)
      --db-maintenance-interval=8h
                                  Database maintenance interval; set to
                                  zero to disable periodic maintenance
                                  ($STDBMAINTENANCEINTERVAL)
      --db-delete-retention-interval=10920h
                                  Database deleted item retention interval
                                  ($STDBDELETERETENTIONINTERVAL)
      --gui-address=URL           Override GUI address (e.g.
                                  "http://192.0.2.42:8443") ($STGUIADDRESS)
      --gui-apikey=API-KEY        Override GUI API key ($STGUIAPIKEY)
      --log-file=PATH             Log file name (see below) ($STLOGFILE)
      --log-level=INFO            Log level for all packages
                                  (DEBUG,INFO,WARN,ERROR) ($STLOGLEVEL)
      --log-max-old-files=N       Number of old files to keep (zero to keep only
                                  current) ($STLOGMAXOLDFILES)
      --log-max-size=BYTES        Maximum size of any file (zero to disable log
                                  rotation) ($STLOGMAXSIZE)
      --log-format-timestamp="2006-01-02 15:04:05"
                                  Format for timestamp, set to empty to disable
                                  timestamps ($STLOGFORMATTIMESTAMP)
      --[no-]log-format-level-string
                                  Whether to include level string in log line
                                  ($STLOGFORMATLEVELSTRING)
      --[no-]log-format-level-syslog
                                  Whether to include level as syslog prefix in
                                  log line ($STLOGFORMATLEVELSYSLOG)
      --no-browser                Do not start browser ($STNOBROWSER)
      --no-port-probing           Don't try to find free ports for GUI
                                  and listen addresses on first startup
                                  ($STNOPORTPROBING)
      --no-restart                Do not restart Syncthing when exiting
                                  due to API/GUI command, upgrade, or crash
                                  ($STNORESTART)
      --no-upgrade                Disable automatic upgrades ($STNOUPGRADE)
      --paused                    Start with all devices and folders paused
                                  ($STPAUSED)
      --unpaused                  Start with all devices and folders unpaused
                                  ($STUNPAUSED)
      --debug-gui-assets-dir=PATH
                                  Directory to load GUI assets from
                                  ($STGUIASSETS)
      --debug-perf-stats          Write running performance statistics to
                                  perf-$pid.csv (Unix only) ($STPERFSTATS)
      --debug-profile-block       Write block profiles to
                                  block-$pid-$timestamp.pprof every 20 seconds
                                  ($STBLOCKPROFILE)
      --debug-profile-cpu         Write a CPU profile to cpu-$pid.pprof on exit
                                  ($STCPUPROFILE)
      --debug-profile-heap        Write heap profiles to
                                  heap-$pid-$timestamp.pprof each time heap
                                  usage increases ($STHEAPPROFILE)
      --debug-profiler-listen=ADDR
                                  Network profiler listen address ($STPROFILER)
      --debug-reset-delta-idxs    Reset delta index IDs, forcing a full index
                                  exchange

Logging always happens to the command line (stdout) and optionally to the
file at the path specified by --log-file=path. In addition to an path, the special
values "default" and "-" may be used. The former logs to DATADIR/syncthing.log
(see --data), which is the default on Windows, and the latter only to stdout,
no file, which is the default anywhere else.

常用参数速查(带真实默认值):

参数(默认值)用途场景
--gui-address(无,读配置)临时覆盖 GUI 监听地址,不改 config.xml多实例、端口冲突临时切换
--gui-apikey(无)覆盖 API KeyCI 环境注入临时凭据
--log-level=INFO日志级别 DEBUG/INFO/WARN/ERROR排障时 --log-level=DEBUG
--log-file=defaultWindows 默认落 DATADIR/syncthing.log,Linux 默认仅 stdoutsystemd 模式日志进 journal
--db-maintenance-interval=8h数据库维护周期0 关闭周期维护
--db-delete-retention-interval=10920h已删除条目保留期(455 天)设备长期离线防误删的保留窗口
--paused / --unpaused启动时全部暂停/恢复计划性停机维护、恢复作业
--no-browser / --no-restart / --no-upgrade禁弹浏览器 / 禁自重启 / 禁自动升级systemd 托管固定组合(官方 unit 即 serve --no-browser --no-restart,deb 另带 noupgrade 版本标记)
--audit / --auditfile=PATH事件审计合规审计场景
--allow-newer-config允许加载更高版本配置降级运行临时绕过

serve 尾部还有开发者环境变量说明,与排障最相关的是 STTRACE(按包开调试日志),有效包名实测清单:

 api             - REST API
 beacon          - Multicast and broadcast discovery
 config          - Configuration loading and saving
 connections     - Connection handling
 db/sqlite       - SQLite database
 dialer          - Dialing connections
 discover        - Remote device discovery
 events          - Event generation and logging
 fs              - Filesystem access
 main            - Main package
 model           - The root hub
 nat             - NAT discovery and port mapping
 pmp             - NAT-PMP discovery and port mapping
 protocol        - The BEP protocol
 relay/client    - Relay client
 scanner         - File change detection and hashing
 stun            - STUN functionality
 syncthing       - Main run facility
 upgrade         - Binary upgrades
 upnp            - UPnP discovery and port mapping
 ur              - Usage reporting
 versioner       - File versioning
 watchaggregator - Filesystem event watcher

用法示例(临时观察发现模块):STTRACE=discover:DEBUG syncthing serve( systemd 服务则在 unit 的 Environment= 注入)。

五、syncthing cli 详解

syncthing cli 面向运行中实例,等价于封装好的 REST 调用。

5.1 cli 命令组总览

syncthing cli --help

实测回显(输出节选,实测首尾):

Usage: syncthing cli <command> [flags]

Command line interface for Syncthing

Flags:
  -h, --help                  Show context-sensitive help.
  -C, --config=PATH           Set configuration directory (config and keys)
                              ($STCONFDIR)
  -D, --data=PATH             Set data directory (database and logs)
                              ($STDATADIR)
  -H, --home=PATH             Set configuration and data directory ($STHOMEDIR)
      --version               Show current version, then exit

      --gui-address=STRING    ($STGUIADDRESS)
      --gui-apikey=STRING     ($STGUIAPIKEY)

Commands:
  cli show          Show command group
  cli debug         Debug command group
  cli operations    Operation command group
  cli errors        Error command group
  cli config        Configuration modification command group
  cli -             Read commands from stdin

cli 自身支持 --gui-address/--gui-apikey 覆盖目标实例(默认读本机配置),可远程管理其他设备。

5.2 cli show:状态查询

syncthing cli show --help

实测回显(Commands 部分):

Commands:
  cli show version          Show syncthing client version
  cli show config-status    Show configuration status, whether or not a restart
                            is required for changes to take effect
  cli show system           Show system status
  cli show connections      Report about connections to other devices
  cli show discovery        Show the discovered addresses of remote devices
                            (from cache of the running syncthing instance)
  cli show usage            Show usage report
  cli show pending          Pending subcommand group

实测 cli show version:

syncthing cli show version

实测回显(输出节选,实测首尾):

{
  "arch": "amd64",
  "codename": "Hafnium Hornet",
  "date": "2026-10-20T19:54:38Z",
  "isRelease": true,
  "longVersion": "syncthing v2.1.7 \"Hafnium Hornet\" (go1.27.3 linux-amd64) debian@github.syncthing.net 2026-10-20 19:54:38 UTC [noupgrade]",
  "os": "linux",
  "version": "v2.1.7"
}

实测 cli show system(输出节选,实测首尾;截取监听与内存关键段):

syncthing cli show system | python3 -m json.tool | head -30

实测回显:

{
    "alloc": 9371584,
    "connectionServiceStatus": {
        "dynamic+https://relays.syncthing.net/endpoint": {
            "error": null,
            "lanAddresses": [
                "relay://171.213.174.222:22067/?id=IPEQNKG-6SYSCPJ-A75IGZU-KD55ELF-COH4ODL-VBAOF7A-6KC3XKK-TEFXQAT"
            ]
        },
        "quic://0.0.0.0:22000": {
            "error": null,
            "lanAddresses": [
                "quic://0.0.0.0:22000",
                "quic://10.89.67.2:22000"
            ]
        }
    }
}

解读:connectionServiceStatus 直接暴露三类监听器(中继池、QUIC、TCP)的实时状态——排障「监听是否起来」看这里最快。

5.3 cli operations:执行操作

syncthing cli operations --help

实测回显(Commands 部分):

Commands:
  cli operations restart     Restart syncthing
  cli operations shutdown    Shutdown syncthing
  cli operations upgrade     Upgrade syncthing (if a newer version is available)
  cli operations folder-override
                             Override changes on folder (remote for sendonly,
                             local for receiveonly). WARNING: Destructive -
                             deletes/changes your data
  cli operations default-ignores
                             Set the default ignores (config) from a file

⚠️ folder-override 为破坏性操作(覆盖 sendonly/receiveonly 文件夹的变更),执行前务必确认方向。日常运维最高频的两个动作——重启与关闭(systemd 场景更推荐 systemctl restart/stop syncthing@root):

syncthing cli operations restart

实测回显:命令成功即静默返回(实例重启进行中);重启后 cli show config-status 可确认是否还有未生效配置。

5.4 cli config:配置修改

syncthing cli config --help

实测回显(Commands 部分):

Commands:

  ACTIONS:
    dump-json  Dump item as json

  PROPERTIES:
    version
    folders
    devices
    gui
    ldap
    options
    ignored-devices
    defaults

每个 property 又分 list/get/set 动作。实测列出全部文件夹:

syncthing cli config folders list

实测回显:

sync-demo

配置修改既可走 cli config,也可走 REST(两者同源),批量模板化场景推荐 REST(见 《Syncthing 2.1.7 配置参数详解》第三章三通道对比)。

六、辅助命令详解

6.1 generate:生成配置与重置 GUI 凭据

syncthing generate --help

实测回显(全文):

Usage: syncthing generate [flags]

Generate key and config, then exit

Flags:
  -h, --help                   Show context-sensitive help.
  -C, --config=PATH            Set configuration directory (config and keys)
                               ($STCONFDIR)
  -D, --data=PATH              Set data directory (database and logs)
                               ($STDATADIR)
  -H, --home=PATH              Set configuration and data directory ($STHOMEDIR)
      --version                Show current version, then exit

      --gui-user=STRING        Specify new GUI authentication user name
      --gui-password=STRING    Specify new GUI authentication password (use - to
                               read from standard input)
      --no-port-probing        Don't try to find free ports for GUI and listen
                               addresses on first startup ($STNOPORTPROBING)

实测重置 GUI 账号(⚠️ v2 必须用 --home 或成对 --config+--data,传位置参数报错,排障实录见安装指南 10.2):

syncthing generate --gui-user=admin --gui-password=q1w2e3r4 --home /root/.local/state/syncthing

实测回显:

2026-10-21 18:17:13 WRN Key exists; will not overwrite (log.pkg=github)
2026-10-21 18:17:13 INF Calculated device ID (device=BITUNOQ-VKBHIFH-2UWCK4D-CCANXZC-GV6VG3E-6JDFMHV-7VZW57L-F3LTKQX log.pkg=github)
2026-10-21 18:17:13 INF Updated GUI authentication user (name=admin log.pkg=github)
2026-10-21 18:17:13 INF Updated GUI authentication password (log.pkg=github)

--gui-password=- 可从标准输入读密码,避免密码进 shell history。

6.2 device-id / version

syncthing device-id

实测回显:

BITUNOQ-VKBHIFH-2UWCK4D-CCANXZC-GV6VG3E-6JDFMHV-7VZW57L-F3LTKQX
syncthing version

实测回显:

Syncthing Version:      v2.1.7 "Hafnium Hornet" (go1.27.3 linux-amd64) debian@github.syncthing.net 2026-10-20 19:54:38 UTC
OS/Arch:                linux-amd64
Labels:                 noupgrade

6.3 decrypt:解密加密文件夹

用于 receiveencrypted(加密中转)场景:中转节点拿到的是密文块,用本命令凭加密密码在别处还原文件。命令形态(syncthing decrypt --help 实测确认):

Usage: syncthing decrypt [--password=STRING] [--to=PATH] [--limit=SIZE] [--verify] FOLDER FILE

参数说明:--password 指定加密密码(推荐 - 从 stdin 读);--to 输出目录;--verify 仅校验不解密。执行时 FOLDER 为加密文件夹 ID、FILE 为其中文件路径。

6.4 paths:目录布局速查

syncthing paths

实测回显(全文):

Configuration file:
        /root/.local/state/syncthing/config.xml

Device private key & certificate files:
        /root/.local/state/syncthing/key.pem
        /root/.local/state/syncthing/cert.pem

GUI / API HTTPS private key & certificate files:
        /root/.local/state/syncthing/https-key.pem
        /root/.local/state/syncthing/https-cert.pem

Database location:
        /root/.local/state/syncthing/index-v2

Log file:
        /root/.local/state/syncthing/syncthing.log

GUI override directory:
        /root/.local/state/syncthing/gui

Default sync folder directory:
        /root/Sync

6.5 upgrade:升级检查

syncthing upgrade --help

实测回显(Commands 与关键参数):

Usage: syncthing upgrade [command [flags]]

Perform or check for upgrade, then exit

Commands:
  upgrade check    Check for an upgrade
  upgrade to       Upgrade to a specific version
  upgrade stable   Upgrade to the latest stable version

⚠️ deb/rpm 包安装的版本带 noupgrade 标记(版本回显 Labels: noupgrade),upgrade check 会提示不可用——升级统一走包管理器(apt upgrade),仅 tar.gz 直装版可自升级。

6.6 debug:数据库维护

syncthing debug --help

实测回显(Commands 部分):

Commands:
  debug reset-database         Reset the database, forcing a full rescan and
                               resync
  debug database-statistics    Display database size statistics
  debug database-counts        Display database folder counts
  debug database-file          Display database file metadata

reset-database 是最后手段:清空索引强制全量重扫与重传(数据本身不受影响,但大库重扫耗时长);database-statistics/database-counts 用于评估索引体积(v2 的库在 index-v2 目录)。

七、服务端工具:strelaysrv 与 stdiscosrv

v2 把两个服务端组件拆成独立 deb 包(实测 apt-get install syncthing-relaysrv syncthing-discosrv 安装为 /usr/bin/strelaysrv、/usr/bin/stdiscosrv,版本与主程序一致 2.1.7)。绝大多数用户直接用官方池,自建适合内网隔离或对官方池不信任的场景。

7.1 strelaysrv(中继服务器)

strelaysrv --help

实测回显(输出节选,实测首尾):

Usage of strelaysrv:
  -debug
        Enable debug output
  -ext-address string
        An optional address to advertise as being available on.
                Allows listening on an unprivileged port with port forwarding from e.g. 443, and be connected to on port 443.
  -global-rate int
        Global rate limit, in bytes/s
  -keys string
        Directory where cert.pem and key.pem is stored (default ".")
  -listen string
        Protocol listen address (default ":22067")

要点:默认监听 :22067;-global-rate 限全局转发速率(字节/秒);客户端侧无需改配置——官方池由 config 的 listenAddress 中 dynamic+https://relays.syncthing.net/endpoint 动态下发(实测 cli show system 的 connectionServiceStatus 可见中继池地址),自建中继需在设备的 listenAddress 中加入 relay://<自建中继IP>:22067。

7.2 stdiscosrv(全局发现服务器)

stdiscosrv --help

实测回显(输出节选,实测首尾):

Usage: stdiscosrv [flags]

Flags:
  -h, --help                       Show context-sensitive help.
      --shutdown-delay=FLOAT-64    Time to wait before shutdown after
                                   receiving a shutdown signal (s)
                                   ($DISCOVERY_SHUTDOWN_DELAY)
  -d, --debug                      Print debug output ($DISCOVERY_DEBUG)
  -v, --version                    Print version and exit

自建后把各设备 config 的 globalAnnounceServer 从 default 改为 https://<发现服务器地址>/v2/ 即切换发现通道(默认值参照 config.xml 实测,见配置篇 5.1)。

八、REST API 要点

syncthing cli 与 Web GUI 的底层是 REST API,自动化运维直接用 curl 即可。约定:请求头 X-API-Key: <apikey>(apikey 在 config.xml <apikey> 字段);本节地址 http://127.0.0.1:8384。

8.1 认证方式实测

三种访问形态的真实回显(无认证 403、浏览器会话需 CSRF、API Key 直通):

curl -s -w '\n%{http_code}\n' http://127.0.0.1:8384/rest/system/version

实测回显:

Forbidden

403

带 Basic Auth(GUI 账号 admin)但无 CSRF 令牌时:

CSRF Error

403

带 API Key:

curl -s -H 'X-API-Key: LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL' http://127.0.0.1:8384/rest/system/version

实测回显:

{
  "arch": "amd64",
  "codename": "Hafnium Hornet",
  "date": "2026-10-20T19:54:38Z",
  "isRelease": true,
  "longVersion": "syncthing v2.1.7 \"Hafnium Hornet\" (go1.27.3 linux-amd64) debian@github.syncthing.net 2026-10-20 19:54:38 UTC [noupgrade]",
  "os": "linux",
  "stamp": "1792526078",
  "tags": [
    "noupgrade"
  ],
  "version": "v2.1.7"
}

结论:脚本调用一律 X-API-Key;浏览器交互才用账号密码 + CSRF 流程(GUI 已封装)。

8.2 系统状态端点

curl -s -H "X-API-Key: LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL" http://127.0.0.1:8384/rest/system/status | python3 -c "import json,sys; d=json.load(sys.stdin); print(json.dumps({k:d[k] for k in ['myID','startTime','uptime','alloc','goroutines','tilde','discoveryEnabled']}, indent=2))"

实测回显:

{
  "myID": "BITUNOQ-VKBHIFH-2UWCK4D-CCANXZC-GV6VG3E-6JDFMHV-7VZW57L-F3LTKQX",
  "startTime": "2026-10-21T18:17:13Z",
  "uptime": 346,
  "alloc": 9533064,
  "goroutines": 101,
  "tilde": "/root",
  "discoveryEnabled": true
}

连接与统计(对端 lastSeen 排查「设备多久没上线」):

curl -s -H "X-API-Key: LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL" http://127.0.0.1:8384/rest/stats/device | python3 -m json.tool

实测回显:

{
    "BITUNOQ-VKBHIFH-2UWCK4D-CCANXZC-GV6VG3E-6JDFMHV-7VZW57L-F3LTKQX": {
        "lastSeen": "1970-01-01T00:00:00Z",
        "lastConnectionDurationS": 0
    },
    "H4EJJ6T-TDBKQFV-AK4FR2S-XCOS326-X3A4NQY-D4HJ7JS-BKYLK3X-IWB6HQB": {
        "lastSeen": "2026-10-21T18:22:59Z",
        "lastConnectionDurationS": 1.9239573079999999
    }
}

错误队列(非空说明有运行错误需要处理):

curl -s -H "X-API-Key: LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL" http://127.0.0.1:8384/rest/system/error

实测回显:

{
  "errors": null
}

8.3 同步状态与操作端点

文件夹状态(state/idle 即全同步;needFiles/needBytes 大于 0 表示有待同步项):

curl -s -H "X-API-Key: LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL" "http://127.0.0.1:8384/rest/db/status?folder=sync-demo" | python3 -m json.tool | head -24

实测回显(输出节选,实测首尾):

{
    "errors": 0,
    "pullErrors": 0,
    "globalFiles": 2,
    "globalBytes": 3145774,
    "localFiles": 2,
    "localBytes": 3145774,
    "needFiles": 0,
    "needBytes": 0,
    "inSyncFiles": 2,
    "inSyncBytes": 3145774
}

触发扫描与查询单文件元数据:

curl -s -X POST -H "X-API-Key: LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL" "http://127.0.0.1:8384/rest/db/scan?folder=sync-demo" -w " [%{http_code}]"

实测回显:

 [200]
curl -s -H "X-API-Key: LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL" "http://127.0.0.1:8384/rest/db/file?folder=sync-demo&file=hello.txt" | python3 -c "import json,sys; d=json.load(sys.stdin); print(json.dumps(d.get('global'), indent=2))"

实测回显(输出节选,实测首尾):

{
  "blocksHash": "o0ZK524L26PDP14Lp5O5td6MUlwPzoWg9GUDKwuN/do=",
  "deleted": false,
  "ignored": false,
  "modified": "2026-10-21T18:20:52.194515727Z",
  "modifiedBy": "BITUNOQ",
  "name": "hello.txt",
  "numBlocks": 1,
  "permissions": "0644"
}

事件流(limit 取最近 N 条;排障时盯 StateChanged/DeviceConnected/FolderSummary):

curl -s -H "X-API-Key: LbDgdphpYTUQiq4SHqzaMbmhR36WY9wL" "http://127.0.0.1:8384/rest/events?limit=3" | python3 -c "import json,sys; d=json.load(sys.stdin); print([(e['id'], e['type']) for e in d])"

实测回显:

[(63, 'StateChanged'), (64, 'StateChanged'), (65, 'StateChanged')]

8.4 配置读写端点

/rest/config 系列即配置篇三通道中的「REST 通道」:GET 读、PATCH 部分更新(即时生效)、PUT 整体替换。常用路径与本文实测过的操作:

端点方法用途
/rest/configGET全量配置 JSON(等价 config.xml)
/rest/config/optionsGET/PATCH全局选项(实测回显见配置篇 3.2)
/rest/config/guiGET/PATCHGUI 段(改绑定地址/账号)
/rest/config/folders/<id>GET/PUT/PATCH单文件夹(实测 PATCH versioning 返回 200)
/rest/config/devices/<id>GET/PUT设备增改(实测 PUT 添加设备,回显见安装指南 9.2)
/rest/config/restart-requiredGET检查是否需重启生效

💡 修改生效模型:PATCH 写入内存即刻生效(实例验证:PATCH 版本器后删除文件即时归档);config.xml 落盘异步进行。涉及监听地址等连接级变更时,restart-required 会返回 true,此时执行 syncthing cli operations restart 或 systemctl 重启。

九、注意事项

  1. v2 与 v1 命令不兼容:v1 的主命令级 flag(如 syncthing --gui-address)在 v2 报 unexpected argument,一律改 syncthing serve --gui-address;脚本迁移先跑 syncthing <子命令> --help 核对。
  2. generate 别覆盖密钥:generate 在已有密钥目录执行只更新 GUI 凭据不会覆盖设备密钥(实测回显 WRN Key exists; will not overwrite),但全新目录执行会生成全新设备身份(设备 ID 变化)。
  3. API Key 是管理凭据:持有 API Key 即可完全控制实例并读写同步数据,日志/工单粘贴 config.xml 时注意脱敏。
  4. 破坏性命令三连:debug reset-database(强制全量重同步)、cli operations folder-override(覆盖变更)、cli operations shutdown(停实例)——生产执行前先备份 config.xml 并确认影响面。
  5. CLI 管理远程实例:syncthing cli --gui-address=tcp://<对端IP>:8384 --gui-apikey=<对端KEY> show system 可跨机管理,前提是对端 GUI 已按安装指南 8.4 改绑远程访问。

十、常见问题

Q1:syncthing cli 报连接拒绝? cli 默认读本机配置直连 127.0.0.1:8384,实例未启动或 GUI 地址被改时失败。先 systemctl is-active syncthing@root,再用 --gui-address 显式指向实际监听地址。

Q2:syncthing upgrade check 不可用? 包管理器安装版带 noupgrade 标记,自升级被禁用(见 6.5 节)。用 apt update && apt upgrade syncthing 升级。

Q3:REST 返回 403 Forbidden / CSRF Error? 403 Forbidden=没带凭据;CSRF Error=带了账号密码但无会话 Cookie。脚本统一改用 X-API-Key(8.1 节三种形态实测对照)。

Q4:哪里能看到 API 全集? 运行中实例自带接口文档:GUI 右下角「操作 → 高级 → REST API」页面,或直接访问 http://127.0.0.1:8384/rest/ 下的端点探索;官方文档 https://docs.syncthing.net/dev/rest.html(2026-10-22 查证)。

十一、参考链接

  1. 官方 REST API 文档:https://docs.syncthing.net/dev/rest.html
  2. 官方 CLI 事件文档:https://docs.syncthing.net/dev/events.html
  3. 官方 STTRACE 调试说明:https://docs.syncthing.net/dev/debugging.html
  4. 本专栏认知篇:《Syncthing 介绍与选型指南》
  5. 本专栏部署篇:《Ubuntu 22.04 安装 Syncthing 指南》
  6. 本专栏配置篇:《Syncthing 2.1.7 配置参数详解》