sh 在CentOS 7上创建一个新用户并准备SSH

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sh 在CentOS 7上创建一个新用户并准备SSH相关的知识,希望对你有一定的参考价值。

#!/bin/bash

# The new user's username (prompt for input)
# Will be stored in variable newUserName
echo -e "\e[92mWhat username should be created? Please Enter:\e[37m"
read -p "Enter new username (no spaces): "  newUserName;
echo -e "\n\e[92mNew user will be called: ${newUserName}\e[37m\n"

# Create new user
echo -e "\e[92mCreating the new user as ${newUserName}\e[37m"
sudo adduser -d /home/"${newUserName}" "${newUserName}"

# Generate a random password and store it
echo -e "\e[92mGenerating new password, storing in /home/${newUserName}/your_password\e[37m"
sudo sh -c "head /dev/urandom | tr -dc A-Za-z0-9 | head -c 32 > /home/"${newUserName}"/your_password"

# Use that password as the user's password
echo -e "\e[92mAdding generated password to the new user\e[37m"
sudo cat /home/"${newUserName}"/your_password | sudo passwd "${newUserName}" --stdin

# Add the user to the wheel group, giving them sudo access
echo -e "\e[92mAdding user to wheel group (for sudo access)\e[37m"
sudo gpasswd -a "${newUserName}" wheel

# Create new directories & files for key-based SSH
echo -e "\e[92mCreating .ssh directory in user's home\e[37m"
sudo mkdir /home/"${newUserName}"/.ssh
echo -e "\e[92mChanging .ssh permissions to 700\e[37m"
sudo chmod -Rf 700 /home/"${newUserName}"/.ssh
echo -e "\e[92mChanging .ssh owner\e[37m"
sudo chown -Rf "${newUserName}:${newUserName}" /home/"${newUserName}"/.ssh

echo -e "\e[92mCreating authorized_keys file\e[37m"
sudo touch /home/"${newUserName}"/.ssh/authorized_keys
echo -e "\e[92mChanging authorized_keys permissions to 600\e[37m"
sudo chmod -Rf 600 /home/"${newUserName}"/.ssh/authorized_keys
echo -e "\e[92mChanging authorized_keys owner\e[37m"
sudo chown -Rf "${newUserName}:${newUserName}" /home/"${newUserName}"/.ssh/authorized_keys

# Additional steps needed
echo -e "\n\n\e[91mFinal step:\n\nFor key-based SSH, add your public key string to /home/"${newUserName}"/.ssh/authorized_keys\e[37m\n\n"

以上是关于sh 在CentOS 7上创建一个新用户并准备SSH的主要内容,如果未能解决你的问题,请参考以下文章

Centos 7搭建Gitlab服务器以及操作(创建项目,创建群组,创建用户,添加密钥)

Linux王子教你安装CentOS 7.4系统

如何添加和删除用户一个CentOS 7服务器上

CentOS 7 - 创建新用户

CentOS 7 上搭建nginx 1.6

Vagrant Box 镜像准备:Packer 打包 Centos 7.9 系统