Last active
May 15, 2025 00:51
-
-
Save Richard-Barrett/49a6e3d9fb98aff91758a450bdc7d442 to your computer and use it in GitHub Desktop.
Add SSH User with Input Options
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| set -e | |
| # Usage help function | |
| show_help() { | |
| cat <<EOF | |
| Usage: $0 <username> <public_ssh_key> [--add-sudo] | |
| This script creates a Linux user, sets up their SSH access, and optionally grants sudo privileges. | |
| Arguments: | |
| <username> The system username to create or configure. | |
| <public_ssh_key> The SSH public key string (in quotes). | |
| Options: | |
| --add-sudo Add the user to the 'sudo' group. | |
| --help Show this help message. | |
| Examples: | |
| $0 newuser "ssh-ed25519 AAAAC3NzaC1lZDI1... newuser@host" | |
| $0 newuser "ssh-ed25519 AAAAC3NzaC1lZDI1... newuser@host" --add-sudo | |
| EOF | |
| } | |
| # Validate root | |
| if [[ "$EUID" -ne 0 ]]; then | |
| echo "❌ This script must be run as root. Use sudo." >&2 | |
| exit 1 | |
| fi | |
| # Handle help flag | |
| if [[ "$1" == "--help" ]]; then | |
| show_help | |
| exit 0 | |
| fi | |
| # Validate argument count | |
| if [[ $# -lt 2 || $# -gt 3 ]]; then | |
| show_help | |
| exit 1 | |
| fi | |
| USERNAME="$1" | |
| PUBKEY="$2" | |
| ADD_SUDO=false | |
| if [[ "$3" == "--add-sudo" ]]; then | |
| ADD_SUDO=true | |
| elif [[ -n "$3" ]]; then | |
| echo "❌ Unknown option: $3" | |
| show_help | |
| exit 1 | |
| fi | |
| # Create user if it doesn't exist | |
| if id "$USERNAME" &>/dev/null; then | |
| echo "✅ User '$USERNAME' already exists." | |
| else | |
| echo "➕ Creating user '$USERNAME'..." | |
| adduser --disabled-password --gecos "" "$USERNAME" | |
| fi | |
| # Add sudo access if requested | |
| if [[ "$ADD_SUDO" == true ]]; then | |
| echo "🛡️ Adding '$USERNAME' to sudo group..." | |
| usermod -aG sudo "$USERNAME" | |
| fi | |
| # Set up SSH access | |
| SSH_DIR="/home/$USERNAME/.ssh" | |
| AUTH_KEYS="$SSH_DIR/authorized_keys" | |
| mkdir -p "$SSH_DIR" | |
| echo "$PUBKEY" > "$AUTH_KEYS" | |
| # Set correct permissions and ownership | |
| chown -R "$USERNAME:$USERNAME" "$SSH_DIR" | |
| chmod 700 "$SSH_DIR" | |
| chmod 600 "$AUTH_KEYS" | |
| echo "🔐 SSH key added for user '$USERNAME'." | |
| [[ "$ADD_SUDO" == true ]] && echo "✅ '$USERNAME' now has sudo privileges." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment