自主实现Telnet流量抓取
根据测试需求,需要抓取Telnet流量包,使用wireshark + Python(socket、telnetlib库)实现
实现代码
主要此处有坑, 根据协议规则,wireshark 默认端口为23 的是Telnet协议, 小编的启动服务的时候未设置23端口,因此怎么抓都回显tcp;
搭建服务端
import socket
def start_server(host, port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(1)
print(f"Server started on {host}:{port}")
while True:
client, addr = server.accept()
print(f"Connected by {addr}")
while True:
data = client.recv(1024)
if not data:
break
print(f"Received: {data.decode()}")
client.sendall(data)
client.close()
if __name__ == "__main__":
HOST = 'ip' # Server address
PORT = 23 # Server port
start_server(HOST, PORT)
“启动”
搭建客户端
客户端这里需要注意,编码的要求,如果你用的非UTF-8,就别写中文;
import telnetlib
def telnet_client(host, port):
with telnetlib.Telnet(host, port) as tn:
while True:
message = input("Enter message: ")
tn.write(message.encode('UTF-8') + b"\n")
response = tn.read_until(b"\n").decode('utf-8')
print(f"Server response: {response.strip()}")
if __name__ == "__main__":
HOST = 'ip' # Server address
PORT = 23 # Server port
telnet_client(HOST, PORT)
这里需要“启动”