连接到服务器并在python中向其发送数据

时间:2016-03-10 08:18:01

标签: python sockets

我有一个服务器地址,我可以通过netcat连接到它。当我通过终端连接到服务器时,服务器给我3个随机数,每个数字都在它自己的行中。我要做的是将前两个数字(前两行)相乘并将它们除以第三个数字,我只有0.1秒来做那个(或更多),所以我写了一个脚本来剥离每一行新行char并将其设置为一个字符串然后它将被转换为一个整数,所以我可以做数学并将我得到的值发送到服务器。所以我的代码就是这个

import socket


adib = socket.socket()

host = 'services.cyberprotection.agency'

port = 9999


adib.connect((host, port))

naruto = adib.recv(1024)

if '\n' in naruto:
    line1, naruto = naruto.split('\n', 1)
    if '\n' in naruto:
        line2, naruto = naruto.split('\n', 1)
        if '\n' in naruto:
            line3, naruto = naruto.split('\n', 1)


akagami = int(line1) * int(line2) / int(line3)



print adib.sendall(str(akagami))




adib.close()

我不知道如何发送akagami的值或至少看到我从发送值中得到的答案,因为我会在发送akagami的值后得到一个标记,我已尝试os.system但是通过终端连接提供的值与通过套接字连接的值不同,因此每次设置新连接时,这三个数字的值都会更改。我也无法控制服务器

1 个答案:

答案 0 :(得分:1)

这应该适用于2.7和3.5:

from socket import *

s = socket(AF_INET, SOCK_STREAM)
addr, port = "services.cyberprotection.agency", 9999
s.connect((addr, port)) # create the connection
data = s.recv(1024) # this receives the 3 numbers
nums = list(map(int, data.split())) # convert from str/bytes to int
print(nums)
ans = nums[0] * nums[1] // nums[2] # double slash means integer division
s.sendall(b"%i" % ans) # send the answer. % formatting works for bytes in Python 3 where .format doesn't (for bytes)
print(ans) # print the answer you calculated
print(s.recv(1024).decode()) # print the one the server sends

绝对不容错,但我希望它能回答你的问题。

示例输出:

[65703, 26296, 60199]
28700
28700

我继续把它放在一个循环中。我只是将输出附加到列表并运行500次。我最初的计划是记录所有输出,看看它是重复还是有一个我可以预测的公式。这样,我可以在请求后立即发送答案而不计算它。但是,我最终甚至不需要。在某些时候,它的反应很快。

data = list(filter(lambda x: "flag" in x.lower(), data))
print(data)  # => ['The flag is: 917035HrQ0PODo#']
相关问题