Created
April 10, 2017 19:59
-
-
Save jamiekurtz/5b3fc1490d57b2345c838814a540c938 to your computer and use it in GitHub Desktop.
This bash script is used on startup of a Docker container that is intended to simply provide and SSH endpoint within an app environment.
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
#!/usr/bin/env bash | |
# This script can add given users as SSH users. Use the following environment variables: | |
# SSH_USERS="name1 name2 name3" | |
# SSH_KEY_name1="ssh key for name1" | |
# SSH_KEY_name2="ssh key for name2" | |
# SSH_KEY_name3="ssh key for name3" | |
# You can set MYAPP on line 22 to any arbitrary string | |
function add_ssh_user | |
{ | |
newuser=$1 | |
newuserkey=$2 | |
echo "Adding $newuser as SSH user..." | |
useradd -s /bin/bash -m $newuser | |
adduser $newuser sudo | |
su - $newuser -c "mkdir -p ~/.ssh && chmod 700 ~/.ssh" | |
su - $newuser -c "echo '$newuserkey' > ~/.ssh/authorized_keys" | |
su - $newuser -c "chmod 600 .ssh/authorized_keys" | |
echo "$newuser ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/MYAPP | |
su - $newuser -c "touch ~/.ssh/environment" | |
printenv | grep -v -E "^(USER|HOME|LOGNAME|PWD)=" >> /home/$newuser/.ssh/environment | |
echo "User $newuser added successfully" | |
} | |
function run_sshd | |
{ | |
echo "running sshd in the foreground..." | |
echo "installing openssh-server and sudo..." | |
apt-get update && apt-get install -y openssh-server sudo | |
mkdir /var/run/sshd | |
if [ -n "$SSH_USERS" ]; then | |
echo "adding at least one SSH user..." | |
IFS=' ' read -r -a names <<< "$SSH_USERS" | |
for name in "${names[@]}" | |
do | |
echo "adding SSH user $name..." | |
key_name='SSH_KEY_'$name | |
pub_key=$(printf '%s' "${!key_name}") | |
add_ssh_user "$name" "$pub_key" | |
done | |
echo "completed adding SSH users" | |
else | |
echo "SSH_USERS not set, no users added for SSH" | |
fi | |
echo "PermitUserEnvironment=yes" >> /etc/ssh/sshd_config | |
echo "ClientAliveInterval 600" >> /etc/ssh/sshd_config | |
echo "ClientAliveCountMax 3" >> /etc/ssh/sshd_config | |
/usr/sbin/sshd -e -p $SSH_PORT -D | |
} | |
run_sshd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment