How to execute a script on sftp connection?

Solution 1:

If you don't want to hack the openssh code you have to use the external sftp server. If you do it is a simple matter of putting a wrapper around it. For example: in sshd_config

Subsystem       sftp    /usr/local/bin/sftp-server

In /usr/local/bin/sftp-server:

#!/bin/sh
mount_special_fs
chroot /my/secret/stuff /usr/libexec/openssh/sftp-server
umount_special_fs

It might be possible to put a wrapper around sshd and launch the wrapper from inetd but launching sshd from inted is discouraged because it is to slow to start up.

Solution 2:

You can also use pam_script, a pam module to execute script from a pam authentication module. You can add it in your pam sshd configuration. URL: http://linux.die.net/man/5/pam_script