I'm trying to set up the following: Allow access to an OpenSSH sftp server via ssh keys only, i.e. no password authentication allowed. SSH keys are generated automatically on the server. The server is intended to be used as a web-hosting server, with one user per website. Only sftp access is allowed for these users, no shell.

In order for new users to be able to retrieve their keys via sftp, we allow them to login by password the first time (only the first time!). The password is sent by SMS and each new user has a limited time to connect and get the keys. After the first successful connection, the password access is disabled and only key-based access is allowed for that user.

I have already configured all steps of this workflow except one: how do I detect when a new user connects for the first time via sftp? Is there any elegant method other than parsing the logs?


2 Answers 2


I can think of two more ways than parsing the logs.

  1. Install incron. You can then create a script to execute when a file is read and closed. That script can lock down password access, etc.
  2. Use OTP (one time passwords). This is a perfect solution. http://www.linotp.org/doc/latest/index.html

I would go with #2, but #1 can be useful if things get more complicated.

  • thanks! they both look like very good ways to solve it -- going to try now.
    – Erion
    Feb 1, 2014 at 14:50

Answering my own question to point out another method that does not require any extra software installed: the PAM module pam_exec. I got the inspiration from here (similar question, different context): In my case it makes sense to put

auth    optional     pam_exec.so /path/to/command

in the /etc/pam.d/ssh file. This runs only when ssh/sftp does password authentication, not when it does key-based authentication. The command in /path/to/command may then

  • assign the user to a group that is only allowed to do key-based authentication (MatchGroup directive in sshd_config).


  • add the username to a simple text file. If you then put "auth required pam_listfile.so item=user sense=deny file=/path/to/text/file" in /etc/pam.d/ssh, the pam_listfile module will take care to reject that user next time.

For excellent tutorials on PAM, including the two modules I mention, see the following links:



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.