Dmi*_*ank 49 ssh background-process
相关问题:启动服务器到客户端的ssh连接
那里的回答对我帮助很大,这个命令可以满足我的需求:
ssh -R 2225:localhost:22 loginOfServerWithPublicIP@publicIP
Run Code Online (Sandbox Code Playgroud)
所以我写了脚本来一直重新连接:
#!/bin/bash
while true; do
echo "try to connect..."
ssh -o ServerAliveInterval=240 -R 2225:localhost:22 user@host
echo "restarting in 5 seconds.."
sleep 5
done
Run Code Online (Sandbox Code Playgroud)
并将其添加到/etc/crontab
. 但是我发现如果我只从 shell 中“手动”执行它,它就可以工作,但是如果它被 cron 调用,ssh 会连接并立即完成。(所以,上面的脚本一直重新连接)
从man ssh
,我发现对于后台连接,我应该用-n
密钥调用它,但它没有帮助。然后,我只是环顾四周寻找类似的脚本,我发现如果我调用它就可以工作tail -f something
,即一些“永无止境”的命令,所以我刚刚创建了一个空文件/tmp/dummy_file
,现在我的 ssh 命令如下所示:
ssh -o ServerAliveInterval=240 -R 2225:localhost:22 -n user@host tail -f /tmp/dummy_file
Run Code Online (Sandbox Code Playgroud)
它现在有效!但是,这个解决方案似乎有点难看,而且我真的不明白这种行为的实际原因。碰巧,我试图调用bash
而不是tail -f
(bash
在我看来也是“永无止境”的命令),但它不起作用。
那么,任何人都可以解释这种行为,以及创建后台 ssh 连接以保持反向 ssh 隧道的正确方法是什么?
phe*_*mer 45
听起来您想要-N
ssh 选项。
-N Do not execute a remote command. This is useful for just forwarding ports
(protocol version 2 only).
Run Code Online (Sandbox Code Playgroud)
0xC*_*22L 22
我强烈建议你考虑autossh
。它具有某些启发式方法,可以确定连接丢失是否是根本原因,并降低重新连接尝试的频率。此外,它使用额外的隧道监控连接,这对于您所询问的场景非常有用。
例如,如果您使用的是 Ubuntu,您可以进行网络搜索autossh upstart
以找到一些关于如何配置 Ubuntu 以便隧道以持久方式保持的有用示例。
我正在使用它来为某些服务始终保持与我的服务器的隧道连接。
slm*_*slm 13
我将第二个@0xC0000022L 的建议和使用autossh
。我用它来维护我的笔记本电脑的 SSH 连接,因为我把它从一个地方带到另一个地方,它可以正常工作。我使用此连接隧道返回端口 25 和 2143 以访问我的个人 SMTP 和 IMAP 服务器。
这是我使用的脚本:
$ more /home/saml/bin/autossh_mail.sh
#!/bin/bash
autossh -M 0 -f -N -L 2025:localhost:25 -L 2143:localhost:143 sam@imap-o
Run Code Online (Sandbox Code Playgroud)
然后Host
我在我的$HOME/.ssh/config
文件中为 host维护一个条目imap-o
。
$ more $HOME/.ssh/config
ServerAliveInterval 15
ForwardX11 yes
ForwardAgent yes
ForwardX11Trusted yes
GatewayPorts yes
Host *
ControlMaster auto
ControlPath ~/.ssh/master-%r@%h:%p
IdentityFile ~/.ssh/id_dsa
Host imap-o
User sam
ProxyCommand ssh sam@mygw.mydom.com nc `echo %h|sed 's/-o//'` %p
Run Code Online (Sandbox Code Playgroud)
该autossh_mail.sh
脚本在我登录时作为我桌面的一部分运行。您可以通过gnome-session-properties
.