引言

这篇文章可以帮助系统管理员或需要进行服务器数据迁移的用户。下面是一个使用 restic 进行服务器数据备份的 文章大纲和核心内容:

过程

备份

在旧服务器上,使用 restic 进行数据备份。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ssh-copy-id user@10.9.65.32 # 复制公钥到新服务器以便免密登录

## 安装 restic
sudo apt install restic
export RESTIC_REPOSITORY=sftp:tenney@10.9.65.32:/path/to/borg/restic/repo
export RESTIC_PASSWORD="1919" # 或者使用密码文件/环境变量
export RESTIC_CACHE_DIR=/dev/sda1/path/to/cache ## 如默认备份目录不够用可指定备份目录
restic init -r $RESTIC_REPOSITORY --cache-dir=$RESTIC_CACHE_DIR

## 备份
sudo restic -r $RESTIC_REPOSITORY backup /home /dev/sda1 --verbose --cache-dir=$RESTIC_CACHE_DIR
restic snapshots -r $RESTIC_REPOSITORY

## 状态查看
restic snapshots -r $RESTIC_REPOSITORY --cache-dir=$RESTIC_CACHE_DIR
restic -r $RESTIC_REPOSITORY stats --cache-dir=$RESTIC_CACHE_DIR

## 备份到本地
sudo restic restore latest --target /path/to/restore/location --verbose --cache-dir=$RESTIC_CACHE_DIR

帐号系统恢复

首先获取所有需要备份的帐号的列表。可以使用 lsll 命令来列出 /home 文件夹的内容来作为账户名列表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/bin/bash

# 获取 /home 目录下的所有文件夹名称(排除 . 和 .. 以及特殊目录)
home_dirs=$(ls -1 /home | grep -vE "^\.$|^\.\.$|^lost\+found$|^dev$|^home$")

# 检查是否找到目录
if [ -z "$home_dirs" ]; then
echo "No directories found in /home to create users for!"
exit 1
fi

# 遍历每个目录名称,创建用户并分配权限
for dir in $home_dirs; do
username="$dir"
echo "Processing user: $username"

# 检查用户是否已存在
if id "$username" >/dev/null 2>&1; then
echo "User $username already exists, skipping creation."
else
# 创建用户,设置主目录为 /home/$username,shell 为 /bin/bash
sudo useradd -d "/home/$username" -s /bin/bash -m "$username"
if [ $? -eq 0 ]; then
echo "User $username created successfully!"
else
echo "Failed to create user $username!"
continue
fi

# 设置用户密码(这里设置为用户名作为密码,可根据需求修改)
echo "$username:$username" | sudo chpasswd
if [ $? -eq 0 ]; then
echo "Password set for user $username!"
else
echo "Failed to set password for user $username!"
fi
fi

# 检查目录是否存在并分配权限
if [ -d "/home/$username" ]; then
# 修改目录的拥有者为对应用户
sudo chown -R "$username:$username" "/home/$username"
if [ $? -eq 0 ]; then
echo "Ownership of /home/$username set to $username!"
else
echo "Failed to set ownership for /home/$username!"
fi

# 设置目录权限为 700(仅用户可读写执行)
sudo chmod -R 755 "/home/$username"
if [ $? -eq 0 ]; then
echo "Permissions of /home/$username set to 755!"
else
echo "Failed to set permissions for /home/$username!"
fi
else
echo "Directory /home/$username does not exist, skipping permission setup."
fi

echo "--------------------------------"
done

echo "Account creation and permission setup completed!"

总结

这样就完成了服务器数据的备份和帐号系统的恢复。使用 restic 进行数据备份是一个高效且安全的方法,可以确保数据在迁移过程中的完整性和安全性。通过脚本自动化帐号创建和权限设置,可以大大减少手动操作的错误和时间消耗。