Skip to content

Instantly share code, notes, and snippets.

@michaelHL
Last active November 1, 2017 07:53
Show Gist options
  • Save michaelHL/82658623845925122c8c9fb69fd57954 to your computer and use it in GitHub Desktop.
Save michaelHL/82658623845925122c8c9fb69fd57954 to your computer and use it in GitHub Desktop.
利用 ssh 穿透

利用 ssh 穿透内网

记号

代号 位置 地址 账户
A 位于公网 a.site usera
B 位于 NAT 之后 localhost userb
C 位于 NAT 之后 localhost userc

操作

  • A:
    • 设置 sshd 设置文件 /etc/ssh/sshd_config: GatewayPorts yes
    • sudo systemctl restart sshd
  • B:
    1. 创建 SSH 密钥, 上传至 A:
      ssh-keygen -t 'rsa'
      ssh-copy-id usera@a.site
      
      一路回车, 密钥不要设置密码
    2. 直接输入 autossh -M 6777 -NR 6766:localhost:22 usera@a.site -i /path/to/id_rsa,
          或者 弄成服务(可能不OK):
      1. 编辑文件 /lib/systemd/system/autossh.service, 设置权限为 644:
        [Unit]
        Description=Auto SSH Tunnel
        After=network-online.target
        [Service]
        User=userb
        Type=simple
        ExecStart=/usr/bin/autossh -M 6777 -NR 6766:localhost:22 usera@a.site -i /path/to/id_rsa
        ExecReload=/bin/kill -HUP $MAINPID
        KillMode=process
        Restart=always
        [Install]
        WantedBy=multi-user.target
        WantedBy=graphical.target
        
      2. 一通令之生效的操作:
        sudo systemctl enable NetworkManager-wait-online
        sudo systemctl enable autossh
        sudo systemctl start autossh
        

开耍:

  • A 连 B: ssh -p 6766 userb@localhost
  • C 连 B: ssh -p 6766 userb@a.site
  • 反向连接时指定动态端口转发(机器 C): ssh -p 6766 -qngfNTD 7677 userb@a.site

超时问题

  • 在 B 和 C 的/etc/ssh/ssh_config后面加上: ServerAliveInterval 60
  • 在 A 机的/etc/ssh/sshd_config后面加上: ClientAliveInterval 60

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment