开发者

How to post a file with telnet or a raw socket?

I'm trying to post a file within a raw socket, I read the RFC, and I think I actually tested a lot of options but I'm now stuck.

By the way, I know I could use pycurl, httplib, etc., but I really want to do it manualy.

Here the request:

POST /upload.php?foo=bar HTTP/1.0
Host: localhost
User-Agent: Mozilla/5.0
Content-Type: multipart/form-data; boundary=9afb0c26-7adf-11e0-b167-1c6f65955350

--9afb0c26-7adf-11e0-b167-1c6f65955350
Content-Disposition: form-data; name="files[]"; filename="image.png"
Content-Type: image/png

#PNG

IHD&#   )IDA##x##       D
                         [##
###b######j
5#r#`IEND#B`#
--9afb0c26-7adf-11e0-b167-1c6f65955350--

All those lines are from an array joins :

"\n".join(lines)

I tried both with \n & \r\n

And I send to CRLF at the end.

I read my images like this:

f = open(file, 'rb')
file_content = ''
whi开发者_Go百科le True:
    chunck = f.read(1024)
    file_content += chunck
    if len(chunck) == 0:
        break;

lines.append(file_content)

Any ideas?


Shouldnt there be a 'Content-Length' in the part-headers?


Since you already figured out the header you will use, I recommend putting it into a multiline string like this:

# An infinitely clever way to make \r\n\r\n at end of header, although technically
# inferior to just going rnrn = '\r\n\r\n' tho.  Shut up...
rnrn = '\n'.join('\r\r\r')[:4]

# remember that each line in an http header must be terminated with \r\n.
# Since multiline strings already add a \n terminator at the end of each line, 
# all that is needed is \r at the end of each line.

header = """POST /upload.php?foo=bar HTTP/1.0\r
Host: localhost\r
User-Agent: Mozilla/5.0\r
Content-Type: multipart/form-data; boundary=9afb0c26-7adf-11e0-b167-1c6f65955350\r
--9afb0c26-7adf-11e0-b167-1c6f65955350\r
Content-Disposition: form-data; name="files[]"; filename="image.png"\r
Content-Type: image/png\r
#PNG\r
IHD&#   )IDA##x##       D\r
                     [##\r
###b######j\r
5#r#`IEND#B`#\r
--9afb0c26-7adf-11e0-b167-1c6f65955350--"""+rnrn

HOST = '' #your hostname here
PORT = 0 #your port here

from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT))

s.send(header)
return_data = s.recv(1024)
s.close()

print('Got back: ', return_data)

And that's pretty much it. The real zen of python is that the actual coding part is really simple, the real challenge is what you're coding with it.

I am writing a HTTP program with raw sockets myself. It will be an xchat script that uses babelfish.yahoo.com to translate messages on IRC from foreign speakers.


Every line of the header must be terminated with CRLF. See here: https://www.rfc-editor.org/rfc/rfc2616#section-5

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜