Ssh – Running a script prior to ssh login … but only once

fedorapamsshsshd

I'm hoping someone can offer some insight on this problem, I found a solution to execute a script before an ssh login. It was done by placing the following line within /etc/pam.d/sshd and allowing pam authentication in /etc/ssh/sshd_config

session    required pam_exec.so /home/pc/myScript.sh

And it worked great, problem I noticed was that after exiting the SSH session the script would run again. This particular behavior completely breaks the purpose my script, is there any way to fix this? I suppose I could write-out/read-from a file on whether its time to execute but I'm wondering if there is a better way.

Additional info

  • OS is Fedora Server ARM 29
  • I determined the script ran twice by executing wall on the shell script
  • Here's my /etc/pam.d/shhd

.

#%PAM-1.0
auth       substack     password-auth
auth       include      postlogin
account    required     pam_sepermit.so
account    required     pam_nologin.so
account    include      password-auth
password   include      password-auth
# pam_selinux.so close should be the first session rule
session    required     pam_selinux.so close
session    required     pam_loginuid.so

### My script
session    required pam_exec.so /home/pc/aScriptThatShouldOnlyRunOncePriorToLogin.sh
###
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session    required     pam_selinux.so open env_params
session    required     pam_namespace.so
session    optional     pam_keyinit.so force revoke
session    optional     pam_motd.so
session    include      password-auth
session    include      postlogin

Best Answer

You can use environnement variables available in PAM like $PAM_TYPE

#!/bin/sh
if [ "$PAM_TYPE" != "open_session" ]
    then exit 0
else
    Your script here

Edit: Ref: http://www.linux-pam.org/Linux-PAM-html/sag-pam_exec.html

Related Question