【问题标题】:How to post a file with telnet or a raw socket?如何使用 telnet 或原始套接字发布文件?
【发布时间】:2011-05-10 08:34:16
【问题描述】:

我正在尝试在原始套接字中发布一个文件,我阅读了 RFC,我想我实际上测试了很多选项,但我现在卡住了。

顺便说一句,我知道我可以使用 pycurl、httplib 等,但我真的很想手动操作。

这里是请求:

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--

所有这些行都来自一个数组连接:

"\n".join(lines)

我都尝试了 \n & \r\n

最后我发送给 CRLF。

我是这样阅读我的图片的:

f = open(file, 'rb')
file_content = ''
while True:
    chunck = f.read(1024)
    file_content += chunck
    if len(chunck) == 0:
        break;

lines.append(file_content)

有什么想法吗?

【问题讨论】:

  • 祝你好运;起初我很想尝试找出问题所在,但转念一想,这真是一个疯狂的想法。我无法想象你为什么要以艰难的方式去做(你有什么样的http错误处理???)当urllib2、twisted或scrapy如此简单时@
  • 那不是raw socket。

标签: python sockets file-upload http-post


【解决方案1】:

部分标题中是否应该有“Content-Length”?

【讨论】:

  • RFC 声明它是可选的,但是我尝试定义一个但没有成功
  • 到底发生了什么?如,服务器端说什么?一些服务器端实现“需要”内容长度,以便他们知道即将到来的内容。
【解决方案2】:

既然你已经确定了你将使用的标题,我建议将它放入 像这样的多行字符串:

# 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)

差不多就是这样。 python真正的禅意在于实际的编码 部分真的很简单,真正的挑战是你用它编码什么。

我自己正在编写一个带有原始套接字的 HTTP 程序。这将是一个 xchat 脚本 使用 babelfish.yahoo.com 翻译 IRC 上来自外国用户的消息。

【讨论】:

  • [george grounds again] 你可能真的想要 - 而不是我如何将代码与标题一起放入,实际上去 """+imgdata+"""... 这样它将是无论您从文件中生成什么图像。
【解决方案3】:

标题的每一行都必须以 CRLF 结束。见这里:https://www.rfc-editor.org/rfc/rfc2616#section-5

【讨论】:

  • 我用 \r\n 和 \n 都试过了,但我总是得到“部分上传文件”
猜你喜欢
  • 2011-09-23
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 1970-01-01
  • 2010-11-10
  • 2010-09-16
  • 1970-01-01
相关资源
最近更新 更多