0
0
Fork 0
mirror of https://github.com/atmoz/sftp.git synced 2024-11-17 12:51:33 -05:00
atmoz-sftp/entrypoint
2015-12-16 19:41:49 +01:00

116 lines
2.7 KiB
Bash
Executable file

#!/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
if $(cat /etc/passwd | cut -d: -f3 | grep -q "$uid"); then
echo "User with UID \"$uid\" already exists, skipping."
return 0
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 `</dev/urandom tr -dc A-Za-z0-9 | head -c256`)"
chpasswdOptions=""
fi
echo "$user:$pass" | chpasswd $chpasswdOptions
cat /home/$user/.ssh/keys/* >> /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
# Create final config
if [ ! -f "$userConfFinalPath" ]; then
# 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"
fi
exec /usr/sbin/sshd -D