手動創建 SVN 倉庫需重複執行 svnadmin create、編輯 svnserve.conf、配置 passwd/authz 等步驟,易出錯且難統一。本文提供生產級 Shell 腳本,實現倉庫創建、匿名訪問禁用、認證授權配置、預設開發組權限的一鍵自動化。
#!/bin/bash
# SVN 倉庫自動創建腳本
# 用法:create_svn_repo.sh [admin_user]
# 依賴:subversion (svnadmin), sed, cat
set -euo pipefail
SVN_ROOT="/svnroot"
REPO_NAME="${1:-}"
ADMIN_USER="${2:-admin}"
if [[ -z "$REPO_NAME" ]]; then
echo "Usage: $0 [admin_user]"
echo "Example: $0 myproject john"
exit 1
fi
REPO_PATH="$SVN_ROOT/$REPO_NAME"
CONF_DIR="$REPO_PATH/conf"
# 1. 創建倉庫
if [[ -d "$REPO_PATH" ]]; then
echo "ERROR: Repository '$REPO_NAME' already exists at $REPO_PATH"
exit 1
fi
echo "Creating repository: $REPO_PATH"
svnadmin create "$REPO_PATH"
# 2. 配置 svnserve.conf
echo "Configuring svnserve.conf..."
cat > "$CONF_DIR/svnserve.conf" < "$CONF_DIR/authz" </dev/null || chown -R apache:apache "$REPO_PATH"
chmod -R 750 "$REPO_PATH"
chmod 640 "$CONF_DIR/authz" "$CONF_DIR/svnserve.conf"
# 5. 提示後續操作
cat <
# 1. 保存腳本並賦權
chmod +x /usr/local/bin/create_svn_repo.sh
# 2. 創建倉庫
create_svn_repo.sh myproject john
# 3. 添加用戶密碼(全局統一管理)
htpasswd -c /svnroot/conf/passwd john
htpasswd /svnroot/conf/passwd jane
htpasswd /svnroot/conf/passwd ci_user
# 4. 根據需要調整 authz 組權限
vim /svnroot/myproject/conf/authz
腳本採用全局密碼文件 + 倉庫級 authz架構:
# /svnroot/conf/passwd
[users]
john = $apr1$hash...
jane = $apr1$hash...
ci_user = $apr1$hash...
# /svnroot/myproject/conf/authz
[groups]
admins = john
developers = jane, dev1, dev2
interns = intern1
ci = ci_user
[/]
@admins = rw
@developers = rw
@interns = r
@ci = r
* =
# 標籤目錄保護:僅管理員可寫
[/tags]
@admins = rw
* = r
# 分支目錄:開發者可建分支
[/branches]
@developers = rw
@admins = rw
* = r
# systemd 服務文件 /etc/systemd/system/svnserve.service
[Unit]
Description=SVN Server
After=network.target
[Service]
Type=forking
User=svn
Group=svn
Environment=SVNROOT=/svnroot
ExecStart=/usr/bin/svnserve -d -r \${SVNROOT} --listen-port=3690
ExecReload=/bin/kill -HUP \$MAINPID
KillMode=process
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable --now svnserve
firewall-cmd --permanent --add-port=3690/tcp
firewall-cmd --reload
#!/bin/bash
# /usr/local/bin/svn_backup.sh
# 熱備份(不鎖定倉庫)
REPO_NAME="$1"
BACKUP_DIR="/backup/svn"
DATE=$(date +%F_%H%M)
mkdir -p "$BACKUP_DIR"
svnadmin hotcopy "/svnroot/$REPO_NAME" "$BACKUP_DIR/${REPO_NAME}_$DATE"
tar czf "$BACKUP_DIR/${REPO_NAME}_$DATE.tar.gz" -C "$BACKUP_DIR" "${REPO_NAME}_$DATE"
rm -rf "$BACKUP_DIR/${REPO_NAME}_$DATE"
# 保留 30 天
find "$BACKUP_DIR" -name "${REPO_NAME}_*.tar.gz" -mtime +30 -delete
通過標準化腳本創建 SVN 倉庫,可確保配置一致性、權限模型統一、新項目接入零門檻。建議將腳本納入 CI/CD 流水線,實現「提交代碼 → 自動創建倉庫 → 配置權限 → 推送通知」全流程自動化。