管理百台數據庫服務器需並行執行命令、收集輸出、處理異常,ClusterShell (clush) 以 Python 實現、輕量無代理、支援節點分組與扇出控制,成為運維利器。本文涵蓋源碼安裝、免密佈署、分組管理、進階用法與故障排查。

# RHEL/CentOS/Fedora
yum install clustershell -y
# 或 dnf install clustershell
# Debian/Ubuntu
apt update && apt install clustershell -y
git clone https://github.com/cea-hpc/clustershell.git
cd clustershell
python3 setup.py install
mkdir -p /etc/clustershell
cp conf/* /etc/clustershell/
/etc/clustershell/groups# 格式:組名: 節點列表(支援擴展語法)
db: db-[01-10]
web: web-[01-20]
cache: redis-[01-03],memcached-[01-02]
all: @db,@web,@cache
# 管理節點生成密鑰對
ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519
# 批量分發公鑰(需先手動輸入一次密碼)
for host in db-{01..10} web-{01..20}; do
ssh-copy-id -i ~/.ssh/id_ed25519.pub "$host"
done
# 或使用 clustershell 內建工具(需先配置一台種子節點)
clush -g all -c ~/.ssh/id_ed25519.pub --dest=/tmp/
clush -g all "cat /tmp/id_ed25519.pub >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
# ~/.ssh/config
Host db-*
HostName %h.internal.example.com
User dbadmin
Port 2222
IdentityFile ~/.ssh/id_ed25519
StrictHostKeyChecking accept-new
| 命令 | 說明 | 典型輸出 |
|---|---|---|
clush -g db "uptime" | db 組並行執行,聚合輸出 | db-[01-10]: 10:00:01 up 100 days, load 0.52 |
clush -b -g db "uptime" | -b 顯示節點前綴,便於區分 | db-01: 10:00:01 up... db-02: 10:00:02 up... |
clush -g db -c script.sh --dest=/tmp/ | 複製文件到所有節點 | 複製狀態統計 |
clush -g db --copy --dest=/opt/ script.sh | 複製並保持權限 | |
clush -g db -L "df -h" | -L 逐行顯示,適合長輸出 | 每行前綴節點名 |
clush -g db -N "cmd" | -N 不聚合相同輸出,顯示所有 |
# 最大並發 20,單命令超時 30 秒
clush -g all -f 20 -t 30 "systemctl restart mysqld"
# 串行執行(敏感操作)
clush -g db -f 1 "mysql -e 'FLUSH LOGS'"
clush -g db "systemctl is-active mysqld"
# 返回碼非 0 表示有節點失敗
# 結合 -N 可看到具體哪台失敗
# 從文件讀取
clush -H "$(cat /tmp/target_hosts.txt)" "hostname"
# 從命令生成
clush -H "$(aws ec2 describe-instances --filters Name=tag:Role,Values=db --query 'Reservations[].Instances[].PrivateIpAddress' --output text)" "uptime"
authorized_keys 權限 (600)、父目錄 (700)、SELinux restorecon -R ~/.sshStrictHostKeyChecking accept-new| 工具 | 架構 | 學習曲線 | 適用場景 |
|---|---|---|---|
| ClusterShell | 無代理、Python、SSH | 低 | 即時命令、文件分發、中小規模 |
| Ansible | 無代理、YAML、模組化 | 中 | 配置管理、應用部署、狀態強制 |
| SaltStack | 代理/無代理、事件驅動 | 高 | 大規模、實時監控、複雜編排 |
| Fabric | Python 庫、腳本化 | 低 | 開發者導向、部署腳本 |
ClusterShell 以「輕量、無代理、原生 SSH、節點組擴展語法」精準切中批量命令執行剛需。配合 ssh-copy-id 批量免密、groups 分組管理、-f/-t 扇出控制,可構建「秒級觸達、可視化輸出、可審計記錄」的運維作業平台。對於「執行命令、看結果、拷文件」的高頻場景,它比 Ansible 更直接、更輕快。