执行 SSH 的登录前脚本

执行 SSH 的登录前脚本

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

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

例子...

Client_SSH >> **{server_script_exec}** >> login_prompt  >> Server       [login failed]

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

我知道我可能会遭受一些洪流侵袭,但我想了解一下登录前的过程。服务器处于受控环境中,不会暴露在 www 中。

答案1

您可以使用聚丙烯酰胺为此。SSH 服务的 PAM 配置位于 中/etc/pam.d/sshd。要在登录过程中的任何操作之前运行命令,请添加如下内容:

auth [default=ignore] pam_exec.so /path/to/some/script

例如,如果我使用/usr/local/bin/foo.sh包含:

#! /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

然后我这样做ssh muru@localhost,我得到了:

$ cat /tmp/log
PAM_RHOST localhost
PAM_RUSER
PAM_SERVICE sshd
PAM_TTY ssh
PAM_USER muru
PAM_TYPE auth

这在密码提示出现之前不会发生,但auth模块是在输入密码后首先运行的 - 毕竟它们会检查用户是否已经过身份验证:

   authentication - authenticate a user and set up user credentials.
   Typically this is via some challenge-response request that the user
   must satisfy: if you are who you claim to be please enter your
   password. Not all authentications are of this type, there exist
   hardware based authentication schemes (such as the use of smart-cards
   and biometric devices), with suitable modules, these may be substituted
   seamlessly for more standard approaches to authentication - such is the
   flexibility of Linux-PAM.

因此,实际上,auth模块在登录之前运行,并且如果第一个auth模块是pam_exec,这几乎是要运行的第一件事。

请注意这[default=ignore]部分 - 由于auth模块对用户进行身份验证,我们不希望脚本的退出状态有任何意义。default=ignore告诉 PAM 忽略 的pam_exec返回值,无论它是什么,这又取决于脚本的退出状态。请参阅man pam.d更多细节。

注意事项:

  • 如果用户在输入任何密码之前退出,则此程序不会运行。
  • 如果用户提供了空的密码(默认 SSH 配置有PermitEmptyPasswords no,因此 SSH 会拒绝这些密码)。
  • SSH 需要具备UsePAM yesPAM 才能使用。

相关内容