有些新装的 VPS 或云主机默认禁止 root 密码登录,只允许普通用户配合 sudo 或 SSH key。临时迁移、救急维护、批量初始化时,可以短时间打开 root 密码登录;用完后建议再关回去,或者至少换成高强度密码并限制来源 IP。
本文以 Debian、Ubuntu 等使用 OpenSSH 的 Linux 系统为例。
1. 设置 root 密码
先把 root 密码写入系统。把 YOUR_STRONG_PASSWORD 换成自己的强密码:
echo 'root:YOUR_STRONG_PASSWORD' | sudo chpasswd如果密码里有空格、!、$ 等特殊字符,一定要用单引号包起来,避免被 shell 解释。
例如密码是 change passwd,命令应写成:
echo 'root:change passwd' | sudo chpasswd2. 开启 root SSH 登录
修改 OpenSSH 服务端配置:
sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config这两行分别表示:
PermitRootLogin yes:允许 root 通过 SSH 登录。PasswordAuthentication yes:允许使用密码认证。
如果原配置文件里没有这两个字段,可以手动追加:
grep -q '^PermitRootLogin' /etc/ssh/sshd_config || echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config
grep -q '^PasswordAuthentication' /etc/ssh/sshd_config || echo 'PasswordAuthentication yes' | sudo tee -a /etc/ssh/sshd_config3. 一次性永久开启
如果确认这台机器以后都允许 root 使用密码 SSH 登录,可以用下面这组命令一次性写入配置。它会先设置 root 密码,再把 SSH 服务端配置改成永久允许 root 密码登录,重启 SSH 后立即生效,系统重启后也会继续保留。
echo 'root:YOUR_STRONG_PASSWORD' | sudo chpasswd
sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config
grep -q '^PermitRootLogin' /etc/ssh/sshd_config || echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config
grep -q '^PasswordAuthentication' /etc/ssh/sshd_config || echo 'PasswordAuthentication yes' | sudo tee -a /etc/ssh/sshd_config
sudo sshd -t
sudo systemctl restart ssh如果系统的 SSH 服务名是 sshd,最后一行改成:
sudo systemctl restart sshd永久开启后尤其要注意密码强度,建议同时限制来源 IP、开启防火墙,或只在可信管理网络里开放 22 端口。
4. 检查配置并重启 SSH
先检查配置语法:
sudo sshd -t没有输出通常表示配置语法通过。
systemd 系统一般这样重启:
sudo systemctl restart ssh如果服务名不是 ssh,试试:
sudo systemctl restart sshdAlpine、OpenRC 或其他系统可能使用:
sudo service sshd restart5. 验证登录
不要立刻关闭当前 SSH 窗口。另开一个终端测试 root 登录:
ssh root@SERVER_IP能输入密码并登录成功后,再关闭旧窗口。
如果登录失败,先看服务状态:
sudo systemctl status ssh --no-pager
sudo journalctl -u ssh -n 80 --no-pager如果系统服务名是 sshd,把上面的 ssh 改成 sshd。
6. 用完后建议关回去
如果只是临时救急,用完后建议关闭 root 密码登录:
sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin prohibit-password/g' /etc/ssh/sshd_config
sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/g' /etc/ssh/sshd_config
sudo sshd -t
sudo systemctl restart sshPermitRootLogin prohibit-password 表示 root 不能用密码登录,但仍可使用 SSH key。生产环境更推荐 SSH key、限制来源 IP、修改默认端口或配合防火墙。
7. 临时开启的一次性命令
如果确认只是临时开启,可以按下面顺序执行。记得把密码换掉:
echo 'root:YOUR_STRONG_PASSWORD' | sudo chpasswd
sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config
sudo sshd -t
sudo systemctl restart ssh如果 systemctl restart ssh 报服务不存在,再执行:
sudo systemctl restart sshd