#!/bin/bash set -e userConfPath="/etc/sftp-users.conf" userConfFinalPath="/var/run/sftp-users.conf" function printHelp() { echo "Add users as command arguments, STDIN or mounted in $userConfPath" echo "Syntax: user:pass[:e][:uid[:gid]]..." echo "Use --readme for more information and examples." } function printReadme() { cat /README.md echo "TIP: Read this in HTML format here: https://github.com/atmoz/sftp" } function createUser() { IFS=':' read -a param <<< $@ user="${param[0]}" pass="${param[1]}" if [ -z "$user" ]; then echo "You must at least provide a username." printHelp exit 1 fi if [ "${param[2]}" == "e" ]; then chpasswdOptions="-e" uid="${param[3]}" gid="${param[4]}" else uid="${param[2]}" gid="${param[3]}" fi useraddOptions="--no-user-group" if [ -n "$uid" ]; then useraddOptions="$useraddOptions --non-unique --uid $uid" fi if [ -n "$gid" ]; then useraddOptions="$useraddOptions --gid $gid" if ! $(cat /etc/group | cut -d: -f3 | grep -q "$gid"); then groupadd --gid $gid $gid fi fi useradd $useraddOptions $user chown root:root /home/$user chmod 755 /home/$user if [ -z "$pass" ]; then pass="$(echo `> /home/$user/.ssh/authorized_keys chown $user /home/$user/.ssh/authorized_keys chmod 600 /home/$user/.ssh/authorized_keys } if [[ $1 =~ ^--help$|^-h$ ]]; then printHelp exit 0 fi if [ "$1" == "--readme" ]; then printReadme exit 0 fi # Append mounted config to final config if [ -f "$userConfPath" ]; then cat "$userConfPath" >> "$userConfFinalPath" fi # Append users from arguments to final config for user in "$@"; do echo "$user" >> "$userConfFinalPath" done # Append users from STDIN to final config if [ ! -t 0 ]; then while IFS= read -r user || [[ -n "$user" ]]; do echo "$user" >> "$userConfFinalPath" done fi if [ ! -f "$userConfFinalPath" ]; then echo "ERROR: Missing users!" printHelp exit 1 fi # Import users from final conf file while IFS= read -r user || [[ -n "$user" ]]; do createUser "$user" done < "$userConfFinalPath" exec /usr/sbin/sshd -D