dlx-ansible/scripts/create-user.sh

95 lines
2.9 KiB
Bash
Executable File

#!/bin/bash
# Create a user with sudo privileges
# Usage: ./create-user.sh [username]
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Default username
USERNAME="${1:-dlxadmin}"
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo -e "${RED}Please run as root or with sudo${NC}"
exit 1
fi
echo -e "${GREEN}Creating user: ${USERNAME}${NC}"
# Check if user already exists
if id "$USERNAME" &>/dev/null; then
echo -e "${YELLOW}User ${USERNAME} already exists${NC}"
else
# Create user
useradd -m -s /bin/bash "$USERNAME"
echo -e "${GREEN}User ${USERNAME} created${NC}"
fi
# Set password
echo -e "${YELLOW}Set password for ${USERNAME}:${NC}"
passwd "$USERNAME"
# Add to sudo group (Debian/Ubuntu) or wheel (RHEL/CentOS)
if getent group sudo &>/dev/null; then
usermod -aG sudo "$USERNAME"
echo -e "${GREEN}Added ${USERNAME} to sudo group${NC}"
elif getent group wheel &>/dev/null; then
usermod -aG wheel "$USERNAME"
echo -e "${GREEN}Added ${USERNAME} to wheel group${NC}"
else
echo -e "${RED}Neither sudo nor wheel group found${NC}"
fi
# Configure passwordless sudo
if [ -d /etc/sudoers.d ]; then
echo "$USERNAME ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/"$USERNAME"
chmod 440 /etc/sudoers.d/"$USERNAME"
echo -e "${GREEN}Configured passwordless sudo for ${USERNAME}${NC}"
else
# Fallback: add to sudoers file directly
if ! grep -q "^$USERNAME" /etc/sudoers; then
echo "$USERNAME ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
echo -e "${GREEN}Added ${USERNAME} to /etc/sudoers${NC}"
fi
fi
# Check and install SSH server
if ! command -v sshd &>/dev/null && ! systemctl list-unit-files | grep -q sshd; then
echo -e "${YELLOW}SSH server not found. Installing...${NC}"
if command -v apt-get &>/dev/null; then
apt-get update && apt-get install -y openssh-server
elif command -v dnf &>/dev/null; then
dnf install -y openssh-server
elif command -v yum &>/dev/null; then
yum install -y openssh-server
elif command -v pacman &>/dev/null; then
pacman -Sy --noconfirm openssh
else
echo -e "${RED}Could not install SSH server. Please install manually.${NC}"
fi
fi
# Enable and start SSH service
if command -v systemctl &>/dev/null; then
systemctl enable --now sshd 2>/dev/null || systemctl enable --now ssh 2>/dev/null
echo -e "${GREEN}SSH service enabled and started${NC}"
fi
# Setup .ssh directory
mkdir -p /home/"$USERNAME"/.ssh
chmod 700 /home/"$USERNAME"/.ssh
touch /home/"$USERNAME"/.ssh/authorized_keys
chmod 600 /home/"$USERNAME"/.ssh/authorized_keys
chown -R "$USERNAME":"$USERNAME" /home/"$USERNAME"/.ssh
echo -e "${GREEN}Created .ssh directory${NC}"
echo -e "${GREEN}✓ User ${USERNAME} setup complete!${NC}"
echo -e "${YELLOW}Now run from your ansible workstation:${NC}"
echo -e " ./scripts/setup-ssh.sh <this-server-ip> ${USERNAME}"