Created
January 3, 2016 13:59
-
-
Save so0k/acddd9fd82a064b441d1 to your computer and use it in GitHub Desktop.
sshcommand.sh
This file contains 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 | |
shopt -s nocasematch #For case insensitive string matching, for the first parameter | |
SELF=`which $0` | |
case "$1" in | |
create) # sshcommand create <user> <command> | |
if [[ $# -ne 3 ]]; then | |
echo "Usage : sshcommand create user command" | |
exit -1 | |
fi | |
USER="$2"; COMMAND="$3" | |
if id -u $USER >/dev/null 2>&1; then | |
echo "User '$USER' already exists" | |
else | |
#alpine: create without password, bash shell and unlock | |
adduser -s /bin/bash -D $USER | |
passwd -u $USER | |
fi | |
USERHOME=$(sh -c "echo ~$USER") | |
mkdir -p "$USERHOME/.ssh" | |
touch $USERHOME/.ssh/authorized_keys | |
echo "$COMMAND" > "$USERHOME/.sshcommand" | |
chown -R $USER $USERHOME | |
;; | |
acl-add) # sshcommand acl-add <user> <identifier> | |
if [[ $# -ne 3 ]]; then | |
echo "Usage : sshcommand acl-add user identifier" | |
exit -1 | |
fi | |
USER="$2"; NAME="$3" | |
getent passwd $USER > /dev/null || false | |
USERHOME=$(sh -c "echo ~$USER") | |
KEY=$(cat) | |
#source /etc/profile to get any environment variables pushed there | |
FINGERPRINT=$(ssh-keygen -lf /dev/stdin <<< $(echo $KEY) | awk '{print $2}') | |
KEY_PREFIX="command=\". /etc/profile;FINGERPRINT=$FINGERPRINT NAME=$NAME \`cat $USERHOME/.sshcommand\` \$SSH_ORIGINAL_COMMAND\",no-agent-forwarding,no-user-rc,no-X11-forwarding,no-port-forwarding" | |
echo "$KEY_PREFIX $KEY" >> "$USERHOME/.ssh/authorized_keys" | |
echo $FINGERPRINT | |
;; | |
acl-remove) # sshcommand acl-remove <user> <identifier> | |
if [[ $# -ne 3 ]]; then | |
echo "Usage : sshcommand acl-remove user identifier" | |
exit -1 | |
fi | |
USER="$2"; NAME="$3" | |
getent passwd $USER > /dev/null || false | |
USERHOME=$(sh -c "echo ~$USER") | |
sed --in-place "/ NAME=$NAME /d" "$USERHOME/.ssh/authorized_keys" | |
;; | |
help|*) # sshcommand help | |
echo "Usage : sshcommand create user command" | |
echo " sshcommand acl-add user identifier" | |
echo " sshcommand acl-remove user identifier" | |
echo " sshcommand help # shows this usage message" | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment