我有这两个 python 脚本。
服务器:
#!/bin/env python
#--*-- coding:UTF-8 --*--
import socket
connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input("Ip : ")
port = int(input("Port : "))
connexion.connect((host, port))
print("The connection with {} is done.".format(host, port))
started = True
while started:
choice = int(input(" [1] Command\n [2] Leave\n > "))
if choice == 1:
command = input(" Command : ")
connexion.send(command.encode())
retour = connexion.recv(1024).decode('latin1')
print(retour)
if choice == 2:
connexion.send("exit")
connexion.close()
break
和客户:
#!/bin/env python
#--*-- coding:UTF-8 --*--
import socket
import subprocess
connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ''
port = 631
connexion.bind((host,port))
connexion.listen(5)
connexion_client, infos_connexion = connexion.accept()
started = True
while started:
rcv_cmd = connexion_client.recv(1024)
rcv_cmd = rcv_cmd.decode()
if rcv_cmd != "exit":
cmd = subprocess.Popen(rcv_cmd, shell=true, stdout = subprocess.PIPE, stderr =subprocess.PIPE, stdin = subprocess.PIPE )
out = cmd.stdout.read() + cmd.sdterr.read()
connexion_client.send(out)
else:
started = False
conexion.close()
exit
这两个脚本在我的本地网络上工作得很好,但是如果我想在两个不同的网络上使用它,我该怎么做呢?关于如何学习如何做到这一点,您有任何链接/提示吗?
请您参考如下方法:
要实现这两个服务器之间的数据传输,您需要 port forward运行服务器的计算机。为此,您需要访问路由器的控制面板。然后指令根据你的路由器而有所不同,但是你需要告诉路由器将服务器的本地IP和端口转发到公共(public)IP和端口。
之后,您应该能够使用服务器路由器的公共(public) IP 从客户端连接到您的服务器。
