《一些常用的VPS指令》的特色图片

一些常用的VPS指令

经常在维护服务器和发布文章时会有很多时候忘记一些服务器指令,把最常用的进行整理和归纳,有利于提高效率。

域名证书的管理

  1. 一键申请域名证书
    certbot certonly --nginx -d aaa.bbb.com
    
  2. 列出所有的域名证书
    sudo certbot certificates
    
  3. 删除指定域名的证书
    sudo certbot delete --cert-name example.com
    
  4. 删除相关文件(可选)
    Certbot 通常会自动删除与证书相关的文件,如果你想手动检查或清理,可以进入以下目录:
    • /etc/letsencrypt/live/
    • /etc/letsencrypt/renewal/
    • /etc/letsencrypt/archive/

用户管理

以下操作均以 root 身份执行,假设新用户名为 luxen,请替换为你实际的用户名。

创建 sudo 用户(Debian 13)

方法一:adduser(交互式,推荐)

# 创建用户(会提示设置密码和基本信息)
adduser luxen

# 加入 sudo 组
usermod -aG sudo luxen

# 验证
groups luxen
# 输出应包含: luxen : luxen sudo

方法二:useradd(一步到位,跳过交互)

useradd -m -s /bin/bash -G sudo luxen && passwd luxen

免密 sudo

echo "luxen ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/luxen
chmod 440 /etc/sudoers.d/luxen

配置 SSH 密钥登录

# 创建 .ssh 目录
mkdir -p /home/luxen/.ssh
chmod 700 /home/luxen/.ssh

# 写入公钥(替换为你的公钥内容)
echo "ssh-ed25519 AAAA..." > /home/luxen/.ssh/authorized_keys
chmod 600 /home/luxen/.ssh/authorized_keys
chown -R luxen:luxen /home/luxen/.ssh

删除用户

# 删除用户及其 home 目录
sudo userdel -r <用户名>

查看所有用户

cat /etc/passwd | grep -v nologin

禁用/锁定用户

# 完全锁定用户
sudo usermod -L -e 1 <用户名>

# 恢复解封用户
sudo usermod -U -e "" <用户名>

踢下线并封禁 SSH

# 封禁前先踢下线,结束所有进程
sudo pkill -u <用户名>

# 禁止该用户 SSH 登录(编辑 /etc/ssh/sshd_config,添加)
DenyUsers <用户名>

# 重启 SSH
sudo systemctl restart ssh

SSH 密钥管理

本地生成 ed25519 密钥对

# 生成 ed25519 密钥(推荐,比 RSA 更安全更快)
ssh-keygen -t ed25519 -C "your-email@example.com"

# 指定文件名(多密钥场景)
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_<服务器名> -C "your-email@example.com"

复制公钥到 VPS

# 方法1:ssh-copy-id(推荐)
ssh-copy-id -i ~/.ssh/id_ed25519.pub <用户名>@<服务器IP>

# 方法2:手动追加(适用于无 ssh-copy-id 的 Windows)
cat ~/.ssh/id_ed25519.pub | ssh <用户名>@<服务器IP> "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

VPS 上配置 SSH 安全

编辑 /etc/ssh/sshd_config

# 禁用 root 密码登录
PermitRootLogin prohibit-password
# 禁用密码登录(仅密钥)
PasswordAuthentication no
# 仅允许 ed25519 密钥
PubkeyAcceptedKeyTypes ssh-ed25519
# 重启 SSH 服务
sudo systemctl restart sshd

本地 SSH config 简化连接

编辑 ~/.ssh/config

Host <别名>
    HostName <服务器IP>
    User <用户名>
    Port 22
    IdentityFile ~/.ssh/id_ed25519

之后直接 ssh <别名> 即可连接。

GitHub ed25519 密钥配对

生成专用 GitHub 密钥

ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_github -C "your-email@example.com"

添加公钥到 GitHub

# 复制公钥内容
cat ~/.ssh/id_ed25519_github.pub

然后到 GitHub → Settings → SSH and GPG keys → New SSH key,粘贴公钥内容。

或者用 gh CLI:

gh auth login          # 先登录
gh ssh-key add ~/.ssh/id_ed25519_github.pub -t "My VPS Key"

配置 SSH config 指定密钥

编辑 ~/.ssh/config

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_github

测试连接

ssh -T git@github.com
# 成功输出: Hi <用户名>! You have successfully authenticated...

其他指令

  1. 生成 32 字节的加密安全随机数
    openssl rand -hex 32