Oracle Cloud 永久免费 VPS CentOS 系统,默认 opc 登录,不能使用 root;Ubuntu 默认登录账户是 ubuntu。Oracle Cloud 实例初始化时最好配置好 SSH 密钥,要不然可能登录不了。

CentOS 使用 opc + SSH 密钥登录,使用命令 sudo -i 可以切换到 root 权限,但是直接 root 登录会提示:Please login as the user “opc” rather than the user “root”.

使用 root 直接登录

如果你想使用 root 直接登录,可以执行一下以下命令(密码是 ooxxoox,一定替换为复杂一点的密码)

echo root:ooxxoox |sudo chpasswd root
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 service sshd restart

实现开机使用 root 登录

上面方法重启 VPS 会失效?没有实测,按理应该不会。下面方法可以实现开机使用 root 登录,可以使用以下命令(密码是 ooxxoox,一定替换为复杂一点的密码)

编辑 cloud.cfg

vi /etc/cloud/cloud.cfg

在 cloud.cfg 最后加入以下代码

#!/bin/bash
echo root:ooxxoox |sudo chpasswd root
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 service sshd restart

上面两个方法来自:https://wzfou.com/oraclecloud/

初始化实例时开启 root 登录

利用 cloud-init 脚本来开启 root 账号密码登录!脚本:

#!/bin/bash
echo root:ooxxoox |sudo chpasswd root
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 service sshd restart

此方法来自:https://51.ruyo.net/14138.html

高级选项,粘贴 cloud-init 脚本,然后实例初始化完成就可以使用 root + 密码登录 VPS。

不过,实测上面三个方法,都只能使用 root + 密码登录 SSH,root + SSH 密匙登录仍然提示:Please login as the user “opc” rather than the user “root”.

无意中发现玄机其实在 /root/.ssh/authorized_keys 里面。打开这个文件,里面是这样子:

no-port-forwarding,no-agent-forwarding,no-X11-forwarding,command="echo 'Please login as the user \"opc\" rather than the user \"root\".';echo;sleep 10" ssh-rsa ooxxxxxx55524242442……此处省略 1024 万字 ……

红色字体部分为初始化实例时添加的 SSH 公钥,亲测,把 authorized_keys 多余的代码:

no-port-forwarding,no-agent-forwarding,no-X11-forwarding,command="echo 'Please login as the user \"opc\" rather than the user \"root\".';echo;sleep 10"

去掉,就可以愉快的使用 root + SSH 密匙登录。

折腾完检查一下 vi /etc/ssh/sshd_config 文件,下面是参考配置:

PermitRootLogin yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
最后修改日期: 2023年12月24日