假设我这样做nc example.com 1234
,它会返回两个用换行符分隔的数字,我必须将它们相加并重新输入。如果我关闭连接,数字会发生变化,那么我该如何在一个连接中获取 netcat 的输出、对其进行计算并再次输入呢?
答案1
对于有同样问题的人来说,使用python 套接字。
一些可以解决该问题的示例代码:
import socket
#AF_INET for IPv4, SOCK_STREAM for TCP (as opposed to UDP).
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Tell the socket what IP and port number to connect to (must be in two brackets because it needs a tuple).
clientsocket.connect(('example.com', 1234))
#Recieve 1024 bytes of data.
data = clientsocket.recv(1024)
#Split the recieved data by newlines (returns a list).
data = data.split('\n')
#The first and second elements in our list should be the two numbers we need to add together, so we do that.
result = int(data[0]) + int(data[1])
#Send our result to the server.
clientsocket.send(str(result))
#Recieve any response from the server and print it to the screen.
data = clientsocket.recv(1024)
print data