Ubuntu下新增root账户并开启SSH教程

Linux 2023-08-27

1. 获取超级管理员权限

首先,我们需要获取超级管理员权限,执行以下命令:

sudo -i

2. 设置用户权限

username替换为你的用户名,执行以下命令,将用户添加到/etc/sudoers.d/root文件中:

echo ‘username ALL=(ALL:ALL) NOPASSWD:ALL’ | sudo tee -a /etc/sudoers.d/root

3. 开启超权限登录

接下来,我们需要修改/etc/ssh/sshd_config文件,开启超权限登录。执行以下命令:

sudo sed -i -e ‘s/#PermitRootLogin prohibit-password/PermitRootLogin yes/g’
-e ‘s/#PasswordAuthentication yes/PasswordAuthentication yes/g’
/etc/ssh/sshd_config

4. 为用户设置密码

username替换为你的用户名,将password替换为你的密码,执行以下命令设置用户密码:

echo username:password| chpasswd

5. 重启SSH服务

最后,执行以下命令重启SSH服务:

sudo systemctl restart sshd

完成以上步骤后,您已经成功在Ubuntu系统下新增了root账户并开启了SSH服务。

现在,您可以通过SSH远程登录并管理您的Ubuntu系统了。

6.一键脚本

#!/bin/bash

# 定义错误处理函数
handle_error() {
    echo "发生错误: $1"
    exit 1
}

# 获取管理员账号
read -p "请输入管理员账号: " username
if [ -z "$username" ]; then
    handle_error "管理员账号不能为空"
fi

# 获取管理员密码
read -sp "请输入管理员密码: " password
echo
if [ -z "$password" ]; then
    handle_error "管理员密码不能为空"
fi

# 超级管理员
sudo -i

# 设置用户权限
echo "$username ALL=(ALL:ALL) NOPASSWD:ALL" | sudo tee -a /etc/sudoers.d/root || handle_error "设置用户权限失败"

# 开启超权限登录
sudo sed -i -e 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/g' \
 -e 's/#PasswordAuthentication yes/PasswordAuthentication yes/g' \
/etc/ssh/sshd_config || handle_error "开启超权限登录失败"

# 为用户设置密码
echo "$username:$password" | sudo chpasswd || handle_error "设置密码失败"

# 重启ssh
sudo systemctl restart sshd || handle_error "重启SSH服务失败"
echo "操作完成,已为您设置管理员账号和密码。"
  1. 无名 - 2023-11-02

    你好,看完你的博客文章,感觉很不错!希望与你网站首页友情链接