使用Python将登录数据包发送到Minecraft服务器不起作用

时间:2012-03-04 11:50:36

标签: python sockets protocols minecraft struct.pack

我在Python中有以下脚本。它的作用是尝试连接到MineCraft服务器,首先发送“握手”,然后发送登录请求。协议规范可在此处找到:http://wiki.vg/Protocol

无论如何,python脚本运行正常,没有错误。但是,我相当使用我编码第二个数据包错误,因为它发送时,服务器控制台上没有任何内容。播放器没有连接或任何东西。由于“客户端”没有及时登录,它最终会超时并关闭连接。

基本上,无论如何谁对struct.pack()有经验应该能够在这里帮助我。我已经评论了我不确定是否已将所有内容编码正确的行。有关打包数据的详细信息,请参见上面的链接。

任何帮助都会非常赞赏,我对编码/打包数据非常无能为力。 :(

import struct
import socket
import time
import urllib
import urllib2
host = "127.0.0.1"
port = 25566
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

logindata = {'user':'JackBeePee', 'password':'*******', 'version':'12'}
data = urllib.urlencode(logindata)
print('Sending data to login.minecraft.net...')
req = urllib2.Request('https://login.minecraft.net', data)
response = urllib2.urlopen(req)
returndata = response.read() 
returndata = returndata.split(":")
mcsessionid = returndata[3]
del req
del returndata
print("Session ID: " + mcsessionid)
data = {'user':u'JackBeePee','host':u'127.0.0.1','port':25566}


stringfmt = u'%(user)s;%(host)s:%(port)d'
string = stringfmt % data
structfmt = '>bh'
packetbytes = struct.pack(structfmt, 2, len(string))+string.encode('utf-16BE')
s.send(packetbytes)
connhash = s.recv(1024)
print("Connection Hash: " + connhash)
print('Sending data to http://session.minecraft.net/game/joinserver.jsp?user=JackBeePee&sessionId=' + mcsessionid + '&serverId=' + connhash + '...')
req = urllib.urlopen('http://session.minecraft.net/game/joinserver.jsp?user=JackBeePee&sessionId=' + mcsessionid + '&serverId=' + connhash)
returndata = req.read()
if(returndata == 'OK'):
    print('session.minecraft.net says everything is okay, proceeding to send data to server.')
else:
    print('Oops, something went wrong.')

time.sleep(5)

# All above here works perfectly.
enc_user = data['user'].encode('utf-16BE')
#This line is probably where something's going wrong:
packetbytes = struct.pack('>bih', 1, 23, len(data['user'])) + data['user'].encode('utf-16BE') + struct.pack('>hiibBB', 2,0,0,0,0,0)
print(len(packetbytes))
print('Sending ' + packetbytes + ' to server.')
s.send(packetbytes)

while True:
    data = s.recv(1024)
    if data:
        print(data)

1 个答案:

答案 0 :(得分:1)

您似乎没有添加字符串或空字段;

packetbytes = struct.pack('>bihshiibBB', 1, 23, len(data['user']), enc_user, 0, 0, 0, 0, 0, 0)

关于打包格式中的第二个h,Minecraft字符串的长度大于或等于2个字节。所以我假设一个空字符串只是short,其值为0。

修改 上述方法不起作用; s需要一个长度;

packfmt = '>bih{}shiibBB'.format(len(enc_user))
packetbytes = struct.pack(packfmt, 1, 23, len(data['user']), enc_user, 0, 0, 0, 0, 0, 0)