• 常用选项
-i #认证文件
-f #在命令执行之前送入后台
-N #不要执行remote command,在只需做端口转发的时候非常有用
-L #LocalForward
-R #RemoteForward
  • 限制root用户只能通过pubkey验证方式登录,用如下设置:
PasswordAuthentication no
PermitRootLogin without-password
  • 通过RemoteForward在家里访问自己在公司的电脑
# 需要一台服务器,在家里和在公司都能访问到,这里假设就是host服务器
ssh -R 2222:127.0.0.1:22 user@host
# 映射host服务器上的2222端口到本地的22端口
# 这会在服务器上启动一个监听在2222端口上的sshd进程,当我们连接服务器的2222端口时,
# 自动连接到公司电脑的22端口上,也就是ssh登录的默认端口,就可以实现连接了
ssh -p 2222 user@127.0.0.1

# 在本机~/.ssh/config中增加配置
Host remotenode
  Hostname xxx.xxx.xxx.xxx
  User centos
  IdentityFile ~/.ssh/TT_DDX_MacMini
  RemoteForward 2222 127.0.0.1:22
  ExitOnForwardFailure yes
# 可以将命令简化为:ssh remotenode
  • 通过LocalForward访问不对外开放的端口
ssh -L 54320:127.0.0.1:5432 user@host
# 映射本机的54320端口到服务器的5432端口
# 当我们连接本机的54320端口时,也就是连接到了服务器的5432端口
# 当5432端口不对外开放时,可以通过此方法实现访问

# 在本机~/.ssh/config中增加配置
Host localnode
  Hostname xxx.xxx.xxx.xxx
  User centos
  IdentityFile ~/.ssh/TT_DDX_MacMini
  LocalForward 54320 127.0.0.1:5432
  ExitOnForwardFailure yes
# 可以将命令简化为:ssh localnode
  • 利用while实现自动连接
# 可以在~/.bashrc中添加
function autoconnect() {
  while true
  do
    ssh -v -N "$1" #-N参数表示只打开隧道,并不实际登录
    sleep 10
  done
}
alias connectlocal='autoconnect localnode'
alias connectremote='autoconnect remotenode'
# 执行gotunnel实现自动连接

sshd_config选项

AuthorizedKeysFile .ssh/authorized_keys
    指定包含用于用户认证的公钥的文件,可以是绝对路径,也可以是基于用户home目录的相对路径。
PasswordAuthentication yes/no
    设为no,则关闭密码认证,可以通过开启AuthorizedKeysFile来使用密钥认证
PermitRootLogin yes/without-password/forced-commands-only/no
    是否允许root用户登录,默认为yes。
    If this option is set to "without-password", password authentication is
    disabled for root.
    If this option is set to "forced-commands-only", root login with public key
    authentication will be allowed, but only if the command option has been
    specified (which may be useful for taking remote backups even if root login
    is normally not allowed). All other authentication methods are disabled for
    root.
    If this option is set to "no", root is not allowed to log in.

ssh_config选项

BatchMode yes/no
    设为yes时,不再询问密码。在执行脚本或一些批处理任务时很有用。默认为no

问题排查

  • Warning: remote port forwarding failed for listen port 2222

执行ssh命令的时候增加-v参数,可以看到debug信息:

debug1: Authentication succeeded (publickey).
Authenticated to 120.55.92.192 ([120.55.92.192]:22).
debug1: remote forward failure for: listen 2222, connect 127.0.0.1:22

权限认证没有问题,但是却无法正常打开隧道,我猜是端口方面有问题,所以执行了下面的检查:

$ sudo netstat -tlnp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address   Foreign Address  State   PID/Program name
tcp        0      0 127.0.0.1:2222  0.0.0.0:*        LISTEN  10528/sshd
tcp        0      0 0.0.0.0:22      0.0.0.0:*        LISTEN  1338/sshd

监听在端口22上的程序是服务器本来的sshd守护进程,而端口2222上的进程,应该是RemoteForward操作异常结束,但并未清理掉的进程,所以导致再次进行端口映射时操作失败。

解决方案:清理掉2222端口上的程序,重新执行RemoteForward操作。

另外说一句,执行netstat的时候,尽量使用sudo权限,否则无法看到占用该端口的PID和Program name。