Ubuntu SSH反向隧道从外网连接内网

来源:互联网 发布:如何拷贝mac照片 编辑:程序博客网 时间:2024/05/16 19:36

两台机器A和B首先安装openssh,命令:
sudo apt-get install openssh-server

分别在A和B上生成RSA公钥私钥对,命令:
ssh-keygen -t rsa -P ”,

分别把A和B的公钥追加到A和B的authorized_keys中,即A和B的authorized_keys中都应该有A和B的公钥, 命令:
cat ~/id_rsa.pub >> ~/.ssh/authorized_keys

接着在A和B中编辑sshd_config以使用authorized_keys, 命令:

sudo gedit /etc/ssh/sshd_config,
将#Authorized一行取消注释并保存

最后修改authorized_keys的权限并重启sshd服务,命令:
chmod 600 ~/.ssh/authorized_keys
sudo service sshd restart

建立反向隧道,假设A为内网机器,在A上运行命令:
ssh -NR 19527:localhost:22 user@ip
该命令建立A到B的反向隧道 19527可以是任意一个未使用的端口号
由于ssh的反向隧道超时后自动断开,一般使用autossh代替,首先安装autossh,
sudo apt-get install autossh
用下列命令代替上面的ssh命令:
autossh -M 5678 -NR 19527:localhost:22 user@ip
5678也是一个未使用的端口号
更新:使用-M 5678需要保证5678和5679两个端口空闲,很不方便,可以使用下面的命令代替,-M 0代表关闭默认的M功能使用后面的两个参数监控ssh
autossh -M 0 -o “ServerAliveInterval 30” -o “ServerAliveCountMax 3” -NR 19527:localhost:22 user@ip

在B机器使用ssh localhost -p 19527就可以连接到A了, 19527需要保持和上面的端口号19527一致

利用scp可以传递文件,从A下载文件到B:
scp -P 19527 localhost:path/to/file ~/
该命令把A上的file下载到B的~/下
从B上传到A:
scp -P 19528 ~/file localhost:path/to/file
该命令把B上的~/file上传到A上的path
以上命令均在B上执行,因为A是我们要连接的内网的服务器

原创粉丝点击