使用 Python 套接字的意外 HTML 错误响应

Unexpected HTML Error Response using Python Sockets

我正在按照教程使用 Python 找到的套接字 here 从网页中检索 HTML。

我在 Ubuntu 来宾上有一个 Apache 服务器 运行,它为我的网站托管一个 HTML 文件。我在我的主机 OS 的 /etc/hosts 文件上创建了一个 DNS 条目,使该网页可以通过 url vulnerable.

访问

我已经确认我的网页可以从主机上的网络浏览器访问。

我对代码进行了一些修改以适合我的情况。

import socket
import sys  # needed for sys.exit()

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
    print ("Failed to initialize socket")
    sys.exit()

print ("Socket initialized")

host = "vulnerable"
port = 80

try:
    remote_ip = socket.gethostbyname(host)
except socket.gaierror as e:
    print ("Hostname could not be resolved. Exiting")
    sys.exit()

s.connect((remote_ip, port))

print ("Socket Connected to " +host+ " on IP " + remote_ip)

message = "GET /HTTP/1.1\r\n\r\n".encode('utf-8')   # convert string to byte message, otherwise won't send

try:
    s.sendall(message)
except socket.error:
    print ("Send Failed")
    sys.exit()

print ("Message sent successfully")

reply = s.recv(4096)
print (reply)

当我尝试从我的网站检索 HTML 时,出现意外错误 404。

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /HTTP/1.1 was not found on this server.</p>
<hr>
<address>Apache/2.4.10 (Ubuntu) Server at 127.0.1.1 Port 80</address>
</body></html>

我不明白为什么我可以从 Web 浏览器毫无问题地访问我的网页时收到此 404 错误。

这是你的问题

message = "GET /HTTP/1.1\r\n\r\n".encode('utf-8')

您需要指定要检索的资源——这就是您收到 The requested URL /HTTP/1.1 was not found on this server 作为网络服务器响应的原因。您请求的资源 /HTTP/1.1 未找到并导致 404 响应。

message 中确保指定要检索的资源,例如

message = "GET /index.html HTTP/1.1\r\n\r\n".encode('utf-8')