码迷,mamicode.com
首页 > 其他好文 > 详细

通过ssh建立点对点的隧道,实现两个子网通信

时间:2018-02-12 22:23:11      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:otl   网通   ubunt   net   准备   后台   防止   img   any   

查看ssh帮助文档是发现有个-w的参数,说明如下:

     -w local_tun[:remote_tun]
             Requests tunnel device forwarding with the specified tun(4) devices between the client (local_tun) and the
             server (remote_tun).

             The devices may be specified by numerical ID or the keyword “any”, which uses the next available tunnel
             device.  If remote_tun is not specified, it defaults to “any”.  See also the Tunnel and TunnelDevice direc?
             tives in ssh_config(5).  If the Tunnel directive is unset, it is set to the default tunnel mode, which is
             “point-to-point”.

 

可以建立“point-to-point”的隧道,类似于pptp的作用

假设现在有北京和上网两个组网,内外网IP如下:

技术分享图片

 准备工作:

服务端需要开启隧道参数(上图中的上海节点)

vim /etc/ssh/sshd_config;
------------------------------------------------------------------------------
PermitRootLogin yes
PermitTunnel yes
------------------------------------------------------------------------------
service ssh restart#重启sshd服务(ubuntu)

 

 

登录北京的机器操作:

 

ssh -o TCPKeepAlive=yes -o ServerAliveInterval=60 -f -w 10:10  2.2.2.2 true

 

 TCPKeepAlive ServerAliveInterval 两个参数是为了保持连接,防止网络抖动是ssh隧道断掉

-f表示后台运行

-w 10:10 表示两边用于隧道通信的网卡名字为 tun10 ,如果0:0,那两边网卡就是tun0

注意:不要混淆了Linux下面名为tunl0的预设Tunnel界面,请用 ip addr show 命令检查。

执行完成这一步之后连边会同时增加一个tun10名的网卡

此时隧道已经建立,但是两边暂时还不能通信,需要制定两边网卡的ip和启动网卡

#北京
ip addr add 10.1.1.1 peer 10.1.1.2 dev tun10
ip link set tun10 up

#上海

ip addr add 10.1.1.2 peer 10.1.1.1 dev tun10
ip link set tun10 up

 

执行完成上面命令之后 两边已经可以相互ping通了,

如果需要两个子网通信需要指定路由和利用iptables做snat

例如上海访问北京:

上海:
route add -net 192.168.10.0/24 dev tun10#网段为对端(北京)的网段 172.16.10.4上执行
如果需要上海的同一子网的其他机器访问的话需要以下操作
iptables -t nat -A POSTROUTING -s 172.16.10.0/24 -d 192.168.10.0/24 -j SNAT --to 10.1.1.2  # 172.16.10.4上执行
子网内其他机器增加路由
route add -net 192.168.10.0/24 gw 172.16.10.4


北京:
iptables -t nat -A POSTROUTING -s 10.1.1.2  -d 192.168.10.0/24  -j SNAT --to 192.168.10.4

 

 执行完成后在上海的子网 已经可以和北京的子网内其他机器通信了

 

如果需要北京子网也访问上海子网的话

根据上面修改即可;

ssh 隧道还有个有点就是只需要服务端有公网IP就行,客户端不需要有公网IP,只要可以访问服务端的公网IP即可

通过ssh建立点对点的隧道,实现两个子网通信

标签:otl   网通   ubunt   net   准备   后台   防止   img   any   

原文地址:https://www.cnblogs.com/toops/p/8445657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!