端口转发并复制回本地机器

端口转发并复制回本地机器

我通常通过 ssh 登录网络,然后再次通过 ssh 登录到另一台计算机,再登录到我的最终目标计算机。例如家庭服务器,然后登录到我家的其中一台计算机。这看起来像:

user0@inital:> ssh -P port_number user1@server
user1@server:> ssh -P port_number user2@final
user2@final:>

一旦user2@final我想将(scp)复制回user0@inital

例如,我可以进行本地端口转发,并通过服务器将本地计算机复制到远程计算机。user0@initial

 user0@initial:> ssh -L4321:final:22 -p 443 user1@server

这将通过上的端口将本地端口转发4321到上的端口。然后通过运行user0@initialuser1@server22user2@finaluser0@initial

  scp -P 4321 some_file  [email protected]:~/

我可以复制user2@finaluser1@server

问题是如何逆转事情并从 复制user2@finaluser0@initial

感谢您的帮助。

答案1

假设您想在 final 的命令提示符下运行 scp 命令:

# have the local client tell the remote server's sshd to listen on
# port 8765 (randomly chosen) and forward any connection it receives
# to the client which will connect to port 22 locally.
user0@initial:> ssh -R127.0.0.1:8765:127.0.0.1:22 -p 443 user1@intermediate

# On this machine have the client tell this remote server's (final's)
# to listen on port 9876 (randomly chosen) and forward any connection
# that it receives back to this client which will connect it to poirt
# 8765 locally.
user1@intermediate:> ssh -R127.0.0.1:9876:127.0.0.1:8765 user2@final

# Now that you are on the final server (final) you run scp, telling
# it to connect to localhost on port 9876.
# 
# So scp will connec to local (final's) port 9876, which is listened
# to by the local sshd based on our second command above.  That sshd
# will forward the connection to the ssh client that connected to it
# (on intermediate).
# 
# The ssh client on intermediate will connect to localhost:8765 as
# instructed which is a conenction to the sshd on intermediate that
# is listening on that port because it was instructed to do so by the
# ssh client on initial when it connected.
# 
# The sshd on intermediate will forward the conenction back to the
# client on initial which will, as instructed, connect to localhost:22
# on initial.
# 
# All this monkey motion means that now scp on final is "directly"
# connected to port 22 (sshd) on initial and can initiate a login
# and file transfer. to the ssh client that connected to it (on
# intermediate).
user2@final:> scp -P 9876 file_from_final 127.0.0.1:back_at_the_house

请注意,我将所有端口都设置为 127.0.0.1,这可以防止它们被互联网上的其他人利用(但不能防止“服务器”或“最终”上的其他人利用)。

答案2

是的。您需要查看 ssh_config 关键字代理命令

指定用于连接服务器的命令。命令字符串延伸到行尾,并使用用户的 shell“exec”指令执行,以避免 shell 进程延迟。

在命令字符串中,任何出现的“%h”都将替换为要连接的主机名,“%p”替换为端口,“%r”替换为远程用户名。该命令基本上可以是任何内容,并且应该从其标准输入读取并写入其标准输出。它最终应该连接在某台机器上运行的 sshd(8) 服务器,或者在某处执行 sshd -i。主机密钥管理将使用所连接主机的 HostName 来完成(默认为用户输入的名称)。将命令设置为“none”将完全禁用此选项。请注意,对于使用代理命令的连接,CheckHostIP 不可用。

此指令与 nc(1) 及其代理支持配合使用非常有用。例如,以下指令将通过 192.0.2.0 上的 HTTP 代理进行连接:

ProxyCommand /usr/bin/nc -X connect -x 192.0.2.0:8080 %h %p

相关内容