为 SSH 执行登录前脚本

Dus*_*off 6 server command-line bash openssh 14.04

我想知道如何执行本地服务器脚本,例如在打开 ssh 会话时使用 mailx 发送邮件,登录前阶段。

当 ssh 连接进入服务器时,我想在登录前执行脚本。

例子...

Client_SSH >> **{server_script_exec}** >> login_prompt  >> Server       [login failed]
Run Code Online (Sandbox Code Playgroud)

我试过搜索这个,但我似乎只得到登录后执行的脚本,比如通过 .bashrc

我知道我正在接受一些洪水,但是我想了解登录前的过程。服务器处于受控环境中,不会暴露在 www.

mur*_*uru 7

You can use PAM for this. The PAM configuration for the SSH service is in /etc/pam.d/sshd. To run a command before anything in the login process, add something like:

auth [default=ignore] pam_exec.so /path/to/some/script
Run Code Online (Sandbox Code Playgroud)

For example, if I use /usr/local/bin/foo.sh containing:

auth [default=ignore] pam_exec.so /path/to/some/script
Run Code Online (Sandbox Code Playgroud)

And then I do ssh muru@localhost, I get:

$ cat /tmp/log
PAM_RHOST localhost
PAM_RUSER
PAM_SERVICE sshd
PAM_TTY ssh
PAM_USER muru
PAM_TYPE auth
Run Code Online (Sandbox Code Playgroud)

This doesn't happen before the password prompt shows up, but auth modules are the first ones run after the password is entered - they check whether the user is authenticated, after all:

#! /bin/sh

cat <<EOF >>/tmp/log
PAM_RHOST $PAM_RHOST  
PAM_RUSER $PAM_RUSER  
PAM_SERVICE $PAM_SERVICE  
PAM_TTY $PAM_TTY  
PAM_USER $PAM_USER  
PAM_TYPE $PAM_TYPE  
EOF
Run Code Online (Sandbox Code Playgroud)

So, in effect, auth modules run before login, and if the first auth module is pam_exec, that's pretty much the first thing to run.

Note the [default=ignore] part - since auth modules authenticate the user, we don't want the script's exit status to mean anything. default=ignore tells PAM to ignore pam_exec's return value, whatever it may be, which in turn depends on the script's exit status. See man pam.d for more details.

Caveats:

  • This doesn't run if the user just quit before entering any password.
  • This doesn't run if the user provided an empty password (the default SSH configuration has PermitEmptyPasswords no, so SSH rejects those out of hand).
  • SSH needs to have UsePAM yes for it to use PAM.