I need to customize OpenSSH server, so that when a new SSH connection is being made to the server, it runs some command (like running a bash script). This command is supposed to "prepare" the server for the SSH connection.

So, from client side it is just a normal SSH connection: ssh user@server.com

But on the server side, it runs a command, then allows the SSH session to start.

Is this possible with OpenSSH? or do I need to write my own SSH server?

Can the same be done when SSH connection is terminated?

  • 1
    What your OS is? Aug 16, 2020 at 19:10
  • My OS is Ubuntu or can be any other Linux distro
    – Mahdi
    Aug 16, 2020 at 19:12
  • 1
    "then allows the SSH session to start" This is actually pretty vague. The client makes a TCP connection to the server, negotiations encryption, authenticates, and then can create one or more shell sessions, SFTP sessions, TCP port forwards, and so on. At what point in this process should this command run? Should it run for SFTP sessions or sessions that only do port forwarding? If a person makes one SSH connection and runs two different shell commands through it, should the command run twice?
    – Kenster
    Aug 16, 2020 at 21:59

2 Answers 2


Maybe I have misunderstood you but if you want to run a command in the server context as opposed to ForceCommand which runs for the user connection you may want to use a socket activated SSHD installation which is described here:


In case you want to run scripts before sshd is launched, use multiple ExecStart statements where sshd is the last.


Yes, use ForceCommand in sshd_config. It is well described in the manual page for sshd_config:


To allow the connection to proceed, you just execute the original command (stored in SSH_ORIGINAL_COMMAND env. variable) in your wrapper script.

  • The question is about running a command on the server before sshd establishes a connection. I'm not sure your answer matches the issue at hand. Aug 16, 2020 at 19:12

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.