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

Detect when an SSH or SFTP connection has closed

· 52CE 我爱测

I have an application that receives a collection of files by SFTP. I need to know when that session has finished so I can process the batch of files in a group. Currently, I'm using the brute force solution of waiting an hour aft…

问题原文

原帖链接 · alsoeric · CC BY-SA 4.0

I have an application that receives a collection of files by SFTP. I need to know when that session has finished so I can process the batch of files in a group.

Currently, I'm using the brute force solution of waiting an hour after the last file change as a signal that the transfer is done. Is there anything more elegant/reliable than a timeout?

[edit] Adding in response to larsks comment.

In this environment, I only control the receiving end. I can not force the senders to do anything (including sending a flag file or controlling file order) except send the files as a batch. I'm lucky they agreed to use SFTP.

已采纳解答

原帖链接 · u1686_grawity · CC BY-SA 4.0

If you are using OpenSSH (or another SFTP server that uses PAM), set up a custom PAM 'session' module that will be triggered whenever the session is opened or closed.

The standard pam_exec.so can be used for this purpose:

# Skip the next 1 module if the condition fails
session [success=ignore default=1] pam_succeed_if.so quiet user = BatchUpload

session optional pam_exec.so type=close_session /bin/systemctl --no-block start BatchJob.service

(Please don't actually run the entire job directly within the context of PAM. If you have systemd, run your processing "detached" as a systemd service. If you don't have systemd – use Fedora's oddjobd, or have PAM touch a flag file for a cronjob to see, or post a message to some form of message queue, etc.)


For OpenSSH, as long as you're not using ChrootDirectory (though in your case you probably are), the SFTP subsystem can be redirected to a wrapper script that runs the real sftp-server followed by any kind of custom task you want.

Subsystem sftp-server /usr/local/sbin/sftp-server-wrapper.sh

SSH subsystems are just command aliases, running in the user's context without any additional privileges, so the script would need to use sudo/doas in order to use systemctl.

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

资料来源与适用范围

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

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

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