How to create SFTP-only user accounts to kill SSH access
Problem Statement
We wanted to create SFTP-only user accounts that cannot SSH into the server to run commands. There is no built-in approach to this problem that we can find so we created a simple shell script to solve it. Here we will discuss how it works.
Step 1: Create a shell script to run as the user’s shell
Create a shell script called /sbin/sftp-only as follows:
#!/bin/sh if [ "$*" != "-c /usr/libexec/sftp-server" ] then echo “Sorry, ssh access not allowed.” exit fi exec /usr/libexec/sftp-server |
Step 2: Edit user accounts to use this shell script as user’s shell
Modify user accounts using usermod to set the shell to /sbin/sftp-only so that when user tries to SSH to the server, the shell script will display the “Sorry, ssh access not allowed.” message. And when the user tries to connect to the server via a SFTP client, the shell script will get executed and it will start the SFTP server for the user.
How to restrict users to SFTP only instead of full SSH access
In case you want users to have access to files on your server but you don't want them to be able to execute commands you can limit them to sftp only access.
Add a user to your system like you normally do with an password and then run the following command:
usermod -s /usr/libexec/sftp-server username
Then change add the following to /etc/shells to make it a valid shell:
echo '/usr/libexec/sftp-server' >> /etc/shells
Now this user can only run the sftp server as shell