说我做nc example.com 1234
,它返回两个数字,并用换行符分隔,我必须将这些数字加在一起并将其输入回来。如果关闭连接,数字会发生变化,那么如何获得netcat的输出,对其进行数学运算并再次在一个连接中再次输入呢?
说我做nc example.com 1234
,它返回两个数字,并用换行符分隔,我必须将这些数字加在一起并将其输入回来。如果关闭连接,数字会发生变化,那么如何获得netcat的输出,对其进行数学运算并再次在一个连接中再次输入呢?
Answers:
一些示例代码可以解决此问题中的问题:
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