大网数据广告活动
服务器运维问答

How to excute a command when SSH session closes?

· 52CE 我爱测

For example, if I close Putty or just lose Internet connection, how to make the server excute a specific command? Mikael's solution in the comments works perfectly . Thanks for help

问题原文

原帖链接 · dynos01 · CC BY-SA 3.0

For example, if I close Putty or just lose Internet connection, how to make the server excute a specific command?

Mikael's solution in the comments works perfectly . Thanks for help

已采纳解答

原帖链接 · Mikael Levoniemi · CC BY-SA 3.0

Because serverfault defaults my answers to comments, i copied over the proper answer from this post :

The best way to do this would be to use pam.

In /etc/pam.d you will have several files, one of them will be called sshd. If you only want to affect ssh, and not other logins (such as a GUI, or real TTY), you want this file. If you want to affect all logins, you'll want a 'common' file. The name of this other 'common' file varies by distro, but you can track it down by following the include and substack statements in the sshd file until you get to the base file.

Once you've identified the file in /etc/pam.d that you want to use, add a line such as the following to the session section:

session     optional    pam_exec.so quiet /etc/pam_session.sh

This will result in calling /etc/pam_session.sh every time someone logs in and logs out (whether gracefully or ungracefully).

Now you just need to create /etc/pam_session.sh. Below is an example you could use to run something every time someone logs out:

#!/bin/sh
if [ "$PAM_TYPE" = "close_session" ]; then
  something
fi

(don't forget to chmod a+x the script)

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-06-19)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。