目录

「SSH」就是四处耍耍

记录SSH配置及使用技巧.

登录

密钥登录

CentOS 6

# 从本机拷贝到远程机
scp -p port path_of_pub_file user@destinate_ip:~/.ssh/
# 将公钥文件追加到认证文件
cat ~/.ssh/xxx.pub >> ~/.ssh/authorized_keys
# 修改远程机ssh配置,启用rsa登陆
vim /etc/ssh/sshd_config
  # 去除下面三行前的注释
  RSAAuthentication yes
  PubkeyAuthentication yes
  AuthorizedKeysFile      .ssh/authorized_keys
# 测试正常后,可酌情关闭密码登陆
  # 修改 yes -> no
  PasswordAuthentication no
# 重启ssh服务
service sshd restart

反向SSH

场景:有三台计算机A、B、C,其中C处在内网儿,而A与C不在同一网络,B拥有公网ip。 目的:A通过B作为跳板访问C 要点:建立B到C之间的永久SSH隧道,A通过SSH访问B,并借B反向访问C 工具:使用autossh保证可靠的建立反向ssh隧道 建立反向SSH隧道Ubuntu 18.04开机启动

约定

  • 中继服务器(B)系统用户名:relayserver_user
  • 中继服务器地址:yirami.xyz
  • 中继服务器SSH隧道端口:11223
  • 中继服务器监视端口:22334
  • 目的计算机(C)系统用户名:destination_user
  • 目的计算机SSH隧道端口:33445

Pipeline

可靠使用版,暂时无法使用autossh
# 建立无密码ssh登陆中继服务器
# 安装autossh
## Debian系
sudo apt-get install autossh
## RedHat系
sudo yum install autossh
# 建立永久反向SSH隧道,如果建立失败,去掉`-M`参数
autossh -M 22334 -fN -o "PubkeyAuthentication=yes" -o "StrictHostKeyChecking=false" -o "PasswordAuthentication=no" -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R yirami.xyz:11223:localhost:33445 relayserver_user@yirami.xyz
# 可将上述命令加入`/etc/rc.local`实现启动自动运行
sudo ln -fs /lib/systemd/system/rc-local.service /etc/systemd/system/rc-local.service
touch /etc/rc.local
vim /etc/rc.local # 首行添加`#!/bin/bash`
chmod 755 /etc/rc.local

语法解释: -M 22334 @ 指定中继服务器上的监视端口,用于交换监视 SSH 会话的测试数据,独享。

原理理解版
  1. 建立C到B之间的永久SSH隧道
ssh -fN -R 11223:localhost:33445 relayserver_user@yirami.xyz

语法解释: -N @ 仅作端口转发,不执行命令操作 -f @ 后台运行SSH -R [bind_address:]port:host:hostport @ 将host主机hostport端口绑定到远程机port端口

  1. 访问
# 先登录中继服务器
ssh -p 11223 destination_user@localhost
进阶理解版

形式上免去两次ssh登陆

vi /etc/ssh/sshd_config
# 添加
GatewayPorts clientspecified
# 重启sshd
## 基于Debian
sudo /etc/init.d/ssh restart
## 基于RedHat
sudo systemctl restart sshd
service sshd restart
# 建立SSH隧道
ssh -fN -o TCPKeepAlive=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -R yirami.xyz:11223:localhost:33445 relayserver_user@yirami.xyz
# 在中继服务器确认反向SSH隧道建立成功
sudo netstat -nap | grep 11223
# 访问
ssh -p 11223 destination_user@yirami.xyz