我正在尝试使用 PuTTY 进行 SSH 隧道。在我的 Windows 计算机上,我运行 PuTTY,隧道从端口 1556 到 remoteipaddress:1556。在远程服务器上,我运行了一个 Python3 套接字服务器,代码几乎直接取自https://docs.python.org/3/library/socketserver.html。
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print(self.data)
if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 1556
# Create the server, binding to localhost on port 9999
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
在客户端,我有一个简单的 Python3 程序,它只发送 hello world。
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(('localhost', 1556))
print(sock.sendall(bytes('hello world', 'utf-8')))
当我将客户端直接连接到服务器时,我在服务器端看到“hello world”消息:
b'hello world'
启用 PuTTY SSH 隧道后,客户端通过隧道从 localhost:1556 到服务器,我收到 0 个字节:
b''
客户端连接到服务器,但没有通过 SSH 隧道发送数据,我不确定具体原因。
plink 命令行参数:
plink -ssh -L 1556:localhost:1556 192.168.1.5
答案1
我记得同样的问题,可能你忘了encode()
和decode()
你的消息。这是一个有效的套接字示例。
客户:
import socket
ip = "192.168.xxx.yyy" # replace your ip address
# connect to server
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((ip, 8080))
print("CLIENT: connected")
# send a message
msg = "I am CLIENT"
client.send(msg.encode())
# recive a message and print it
from_server = client.recv(4096).decode()
print("Recieved: " + from_server)
# exit
client.close()
服务器:
import socket
ip = "192.168.xxx.yyy" # replace your ip address
# start server
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.bind((ip, 8080))
serv.listen(5)
print("SERVER: started")
while True:
# establish connection
conn, addr = serv.accept()
from_client = ''
print("SERVER: connection to Client established")
while True:
# receive data and print
data = conn.recv(4096).decode()
if not data: break
from_client += data
print("Recieved: " + from_client)
# send message back to client
msg = "I am SERVER"
conn.send(msg.encode())
# close connection and exit
conn.close()
break
更多信息请见这里。