ssh 设置 sockets 代理

1
ssh -qTfnN -D 1080 root@alizs.cc
  • -q: Quiet modle. Causes most warning and diagnostic messages to be suppressed.
  • -T: Disable pseudo-terminal allocation.
  • -f: Requests ssh to go to background just before command execution. This is useful if ssh is going to ask for passwords or passphrases, but the user wants it in the background. This implies -n.
  • -n: Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background.
  • -N: Do not execute a remote command. This is useful for just forwarding ports.
  • -D: Specifies a local “dynamic” application-level port forwarding.
  • `root@alizs.cc`: sockets 代理服务器

更多设置可以参考 ssh

这样就可以将请求通过 sockets5 代理地址 127.0.0.1:1080 转发到代理服务器 alizs.cc,完成翻墙了。不过,这种方式实现的代理,会存在 ssh 经常断开链接的问题。这时候,可以用 autossh 来解决。

使用 autossh 管理 ssh 进程

autossh 是一个用来启动并监控管理 ssh 的程序,在 ssh 断开的时候,autossh 会自动重启 ssh 进程。

安装 autossh (ubuntu)

1
sudo apt-get install autossh

使用方法:

1
autossh [-V] [-M monitor_port[:echo_port]] [-f] [SSH_OPTIONS]

  • -M: specifies monitor port. Overrides the environment variable AUTOSSH_PORT. 0 turns monitoring loop off. Alternatively, a port for an echo service on the remote machine may be specified.
  • -f: run in background (autossh handles this, and does not pass it to ssh). 后台运行,并且 -f 参数不会传给 ssh,因为 ssh 也有 -f 参数。比如,执行 autossh -M 0 -fqTnN -D 1080 root@alizs.cc 的时候,autossh 进程会启动一个 ssh 进程,并且 -qTnN -D 1080 root@alizs.cc 这些参数是会传给 ssh 的,但是 -f 不会传给 ssh。也就是说 ssh 进程会像这样:/usr/bin/ssh -qTnN -D 1080 root@alizs.cc
  • -V: print autossh version and exit.

使用实例:

1
autossh -M 0 -fqTN -D 1080 root@alizs.cc

  • -M: -M 0,表示通过 端口检测 ssh 的连接状态,断开后就会自动重连。
  • -f: 后台运行。
  • -qTN: 是 ssh 的参数。(autossh 不传 -f 给 ssh,-n 也就没意义了。)

运行以上命令之后,可以发现系统里多了两个进程,一个是 autossh,一个是 ssh。其中 ssh 是由 autossh 启动的,autossh 作为 ssh 的守护进程,监测 ssh 的状态,当 ssh 断开之后,会自动重启 ssh。