How to setup SFTP in EC2 allowing file upload
· 約2分
SFTP use SSH protocal, allowing user to transfer files safely. It is a subsystem of SSH, so it runs in port 22.
The name contains FTP, however it is not implements FTP protocal
- It achieves the same function with FTP
- It is widely supported by FTP clients
When you want to transfer files with server, it might be a good choice.
How to setup a sftp user allowing it to upload files into specific folder
The following scripts helps setup a SFTP user in
Save it to .sh file, execute the following commands
chmod +x setup_sftp_user.sh
sudo ./setup_sftp_user.sh vendor
It will prompt you to set the password and configure the rest automatically.
#!/bin/bash
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run as root or use sudo"
exit 1
fi
# Check if username is provided
if [ -z "$1" ]; then
echo "Usage: $0 <username>"
exit 1
fi
USER=$1
# Create user
useradd -m $USER
passwd $USER
# Setup SFTP directories
mkdir -p /var/sftp/$USER/uploads
chown root:root /var/sftp/$USER
chmod 755 /var/sftp/$USER
chown $USER:$USER /var/sftp/$USER/uploads
chmod 755 /var/sftp/$USER/uploads
# Backup sshd_config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
# Add SSH config for user
cat <<EOL >> /etc/ssh/sshd_config
Match User $USER
ChrootDirectory /var/sftp/$USER
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
EOL
# Restart SSH daemon
systemctl restart sshd
# Confirm success
echo "SFTP user '$USER' has been set up successfully."