使用脚本的方式进行创建
网上已经有很多的方式进行修改了,但是我觉得最简单的就是使用脚本的方式,直接在服务器上运行脚本,然后就可以修改了。
- 创建脚本文件,命名为 set_root.sh, 并赋予执行权限 chmod +x set_root.sh
- 执行脚本 bash set_root.sh
- 脚本内容如下:
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #!/bin/bash
check_error() { if [ $? -ne 0 ]; then echo "发生错误: $1" exit 1 fi }
check_root() { if [ "$(id -u)" != "0" ]; then echo "需要 root 权限来运行此脚本。请使用 sudo 或以 root 用户身份运行。" exit 1 fi }
generate_random_password() { random_password=$(openssl rand -base64 12 | tr -dc 'a-zA-Z0-9!@#$%^&*()_-') echo "root:$random_password" | sudo chpasswd check_error "生成随机密码时出错" echo "$random_password" }
modify_sshd_config() { sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak check_error "备份 sshd_config 文件时出错"
sudo sed -i 's/^Include \/etc\/ssh\/sshd_config.d\/\*\.conf/# &/' /etc/ssh/sshd_config check_error "注释掉 Include 行时出错"
if grep -q '^PermitRootLogin' /etc/ssh/sshd_config; then sudo sed -i 's/^PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config check_error "修改 PermitRootLogin 时出错" else echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config > /dev/null check_error "追加 PermitRootLogin 时出错" fi
if grep -q '^PasswordAuthentication' /etc/ssh/sshd_config; then sudo sed -i 's/^PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config check_error "修改 PasswordAuthentication 时出错" else echo 'PasswordAuthentication yes' | sudo tee -a /etc/ssh/sshd_config > /dev/null check_error "追加 PasswordAuthentication 时出错" fi }
restart_sshd_service() { sudo service sshd restart check_error "重启 SSHD 服务时出错" }
main() { echo "请选择密码选项:" echo "1. 生成密码" echo "2. 输入密码" read -p "请输入选项编号:" option
case $option in 1) check_root password=$(generate_random_password) ;; 2) read -p "请输入更改密码:" custom_password echo "root:$custom_password" | sudo chpasswd check_error "修改密码时出错" password=$custom_password ;; *) echo "无效选项 退出..." exit 1 ;; esac
modify_sshd_config restart_sshd_service
echo "密码已成功更改:$password" }
main
|
作者:
JenkinWoo
日期:
05/30, 2024 13:33:28
分类:
Linux
归档:
https://www.65.gs/2024/05/a344aec3d589.html