如何终止后台/分离的 ssh 会话? [英] How do I kill a backgrounded/detached ssh session?
问题描述
我正在使用程序协同和 ssh 隧道
I am using the program synergy together with an ssh tunnel
它有效,我只需要打开一个控制台并输入这两个命令:
It works, i just have to open an console an type these two commands:
ssh -f -N -L localhost:12345:otherHost:12345 otherUser@OtherHost
synergyc localhost
因为我很懒,所以我制作了一个 Bash 脚本,只需在图标上单击一下鼠标即可运行:
because im lazy i made an Bash-Script which is run with one mouseclick on an icon:
#!/bin/bash
ssh -f -N -L localhost:12345:otherHost:12345 otherUser@OtherHost
synergyc localhost
上面的 Bash-Script 也能工作,但现在我也想通过一次鼠标点击杀死协同和 ssh 隧道,所以我必须将协同和 ssh 的 PID 保存到文件中以便以后杀死它们:
the Bash-Script above works as well, but now i also want to kill synergy and the ssh tunnel via one mouseclick, so i have to save the PIDs of synergy and ssh into file to kill them later:
#!/bin/bash
mkdir -p /tmp/synergyPIDs || exit 1
rm -f /tmp/synergyPIDs/ssh || exit 1
rm -f /tmp/synergyPIDs/synergy || exit 1
[ ! -e /tmp/synergyPIDs/ssh ] || exit 1
[ ! -e /tmp/synergyPIDs/synergy ] || exit 1
ssh -f -N -L localhost:12345:otherHost:12345 otherUser@OtherHost
echo $! > /tmp/synergyPIDs/ssh
synergyc localhost
echo $! > /tmp/synergyPIDs/synergy
但是这个脚本的文件是空的.
But the files of this script are empty.
如何获取ssh和synergy的PID?
(我尽量避免 ps aux | grep ... | awk ... | sed ...
组合,必须有更简单的方法.)
How do I get the PIDs of ssh and synergy?
(I try to avoid ps aux | grep ... | awk ... | sed ...
combinations, there has to be an easier way.)
推荐答案
好吧,我不想添加 &在命令结束时,如果控制台 wintow 关闭,连接就会终止......所以我最终得到了一个 ps-grep-awk-sed-combo
well i dont want to add an & at the end of the commands as the connection will die if the console wintow is closed ... so i ended up with an ps-grep-awk-sed-combo
ssh -f -N -L localhost:12345:otherHost:12345 otherUser@otherHost
echo `ps aux | grep -F 'ssh -f -N -L localhost' | grep -v -F 'grep' | awk '{ print $2 }'` > /tmp/synergyPIDs/ssh
synergyc localhost
echo `ps aux | grep -F 'synergyc localhost' | grep -v -F 'grep' | awk '{ print $2 }'` > /tmp/synergyPIDs/synergy
(你可以将grep集成到awk中,但我现在太懒了)
(you could integrate grep into awk, but im too lazy now)
这篇关于如何终止后台/分离的 ssh 会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!