反向ssh,实现外网连接内网

这么个情况:

机器A:处于内网,可以连接B

机器B:处于公网,不能连接A

目标:机器B直连机器A

 

通过反向代理实现:

内网上机器A进行操作:

ssh -f -N -R 11111:localhost:22 username_B@机器B的公网ip

外网上机器B进行操作:

ssh  username_A@localhost -p 11111

这里的11111可以换成不冲突的任意端口号

 

当然,两边的public key要互相添加

 

附:

自动守护脚本

#! /usr/bin/perl
use strict;
use warnings;

while(1){
    my $status=✓
    print "status: $status\n";
    if(!$status){
        &start();
        print "connected\n";
    }
    sleep(3)
}

sub start{
    system("ssh -f -N -R 11111:localhost:22 username_B\@serverB_IP -o ExitOnForwardFailure=yes");
}

sub check{
    my $a=`ps -ef | grep '11111:localhost:22' | grep -v 'grep' | wc -l`;
    my @a=split(/\s+/,$a);
    my $result=$a[0];
    return($result);
}

 

出现Error: remote port forwarding failed for listen port 11111这个错误的解决办法

在机器B上

1,netstat -anp

2,kill PID

 

为了防止ssh自动中断,需要在机器B上定期与机器A通讯

#! /us/bin/perl

while (1) {
    `ssh -p 11111 username_A\@localhost \"echo 1\"`;
    sleep(10)
}

 

posted on 2015-11-18 21:18  云中道长  阅读(1440)  评论(0编辑  收藏  举报

导航