Ent*_*ast 11 server ssh scripts networking
如何在客户端系统与服务器建立 ssh 连接后立即在服务器中自动运行脚本
例如:假设用户将使用 ssh 连接从另一个系统(通过 LAN 连接)登录到我的计算机。那时,应该在我的系统中自动运行一个脚本(python 或 shell)来执行一些验证吗?
如何在服务器系统中自动运行脚本?
Req*_*ist 14
您可以通过将以下参数添加到配置文件 (/etc/ssh/sshd_config) 来实现。
Run Code Online (Sandbox Code Playgroud)ForceCommand Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present. The command is invoked by using the user's login shell with the -c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Specifying a command of “internal-sftp” will force the use of an in-process sftp server that requires no support files when used with ChrootDirectory.
另一种选择是按用户使用 .ssh/rc 文件。
要使用 ForceCommand 方法,您只需ForceCommand /usr/bin/ownscript
在文件底部/etc/ssh/sshd_config
(在服务器上)添加。
该脚本如下所示:
#!/bin/bash
#Script file for ssh
#
#put your commands here
echo "test" > /tmp/test.txt
#
#exit by calling a shell to open for the ssh session
/bin/bash
Run Code Online (Sandbox Code Playgroud)
不要忘记 chmod 脚本 sudo chmod +x /usr/bin/ownscript
小智 5
您可以创建一个/etc/ssh/sshrc
文件。见man 8 ssh
。如果您希望单个用户使用此功能,请使用~/.ssh/rc
.
这是一个示例/etc/ssh/sshrc
,当有人登录您的机器时,它将通过 dbus 通知您。不要忘记chmod +x
:
#!/bin/bash
ip=`echo $SSH_CONNECTION | cut -d " " -f 1`
notify-send -u CRITICAL "SSH connection from ${ip}" "User $USER just logged in from $ip"
Run Code Online (Sandbox Code Playgroud)