Getting 404 error for every page with python socket - python-2.7

I started to learn python. I was trying this piece of code from the book.
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
except Exception as e:
print(e)
try:
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print data
except Exception as e:
print(e)
mysock.close()
It doesn't matter which web page I am trying to connect, I am getting 404 error.
I got the following when I run the code.
HTTP/1.1 404 Not Found
Server: nginx
Date: Tue, 23 May 2017 17:54:54 GMT
Content-Type: text/html
Content-Length: 162
Connection: close
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
You are trying to send a HTTP request but there are multiple things wrong with it. Some of these cause problems while others just get ignored by this specific server:
The line end should be \r\n not \n
The path in the GET request should not be an absolute URL but relative to the server, i.e. /code/romeo.txt. Absolute is acceptable with HTTP/1.1 but you use HTTP/1.0.
The server uses virtual hosting, i.e. multiple host names on the same IP address. Therefore you must specify which host to access using a Host header.
The last item is actually the most important one in this case but the other points should be fixed too. Thus the correct request would look like this
mysock.send('GET /code/romeo.txt HTTP/1.0\r\nHost: www.py4inf.com\r\n\r\n')
For more information please study the HTTP standard, i.e. RFC 1945 for the simpler HTTP/1.0 and RFC 2616 for HTTP/1.1 which is more complex but more used in practice.

Try changing this linemysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n') use this instead mysock.connect(('www.py4inf.com', 80))
mysock.send('GET /code/romeo.txt HTTP/1.0\nHost:www.py4inf.com\n\n'.encode())
the connection should look like this :
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET /code/romeo.txt HTTP/1.0\nHost:www.py4inf.com\n\n'.encode())
while True:
data = mysock.recv(512)
if (len(data) < 1):
break
print(data.decode(),end='')
mysock.close()

Here i made the change for you hope this will help :
Ps: also on line 19 Print (data) or you will get SyntaxError
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mysock.connect(('www.py4inf.com', 80))
#mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
mysock.send('GET /code/romeo.txt HTTP/1.0\nHost:www.py4inf.com\n\n'.encode())
except Exception as e:
print(e)
try:
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print (data)
except Exception as e:
print(e)
mysock.close()

Related

SSLError(MaxRetryError("HTTPSConnectionPool(host='fafcebook.com', port=443)

I am trying to get response from the server for server status with this code
import requests
import urllib3
try:
r = requests.get('https://gookle.com')
print r.status_code
print r.raise_for_status()
except requests.exceptions.Timeout as timeoutext:
print timeoutext
except requests.exceptions.TooManyRedirects as tooMany:
print tooMany
except requests.exceptions.ConnectionError as e:
print ("OOps: Something Else", e)
except requests.ConnectionError as cr:
print cr
The proble is here when I am puting right url like https://www.google.com it is ok but when I put **https://www.gookle.com** wrong url secont time output:
('OOps: Something Else', SSLError(MaxRetryError("HTTPSConnectionPool(host='fafcebook.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLEOFError(8, u'EOF occurred in violation of protocol (_ssl.c:661)'),))",),))

Python 2.7 posting, and getting result from web site

I appreciate the help in advance. I am trying to write a python script that posts an IP address to a site referenced below, and get the results printed out in the terminal or file, and then read the file immediately after.
Here is my script:
#!/usr/bin/env python
import requests
IP = raw_input("Enter IP address here: ")
Alert_URL = 'http://www.blacklistalert.org'
def submit_form():
"""Submit a form"""
payload = IP
# make a get request
resp = requests.get(Alert_URL)
print "Response to GET request: %s" % resp.content
# send POST request
resp = requests.post(Alert_URL, payload)
print "Headers from a POST request response: %s" % resp.headers
# print "HTML Response: %s" %resp.read()
if __name__ == '__main__':
submit_form()
The site has section to input IP addresses on the web page, and inspecting the site I found lines to input as follows:
<form method=POST onsubmit="document.forms[0].submit.disabled='true';">
IP or Domain <input onclick="this.value='';" name=q value=11.11.154.23>
I would like to post an IP address that I want to check to the site using the input section above somehow. For instance using raw_input to post into the 'value=' section, and get the result.
Thanks for the help.
You need to parse the PHPSESSID and post:
import requests
from bs4 import BeautifulSoup
ip = raw_input("Enter IP address here: ")
data = {"q": ip} # ip goes here
url = "http://www.blacklistalert.org/"
with requests.Session() as s:
# get the page first to parse
soup = BeautifulSoup(s.get(url).content)
# extract and add the PHPSESSID
PHPSESSID = soup.select_one("input[name=PHPSESSID]")["value"]
data["PHPSESSID"] = PHPSESSID
# finally post
res = s.post(url, data=data)
print(res)
print(res.content)

python 2.7 400 Bad Request Error

I am doing an exercise for an online course and keep getting an error thrown at me. Theres another 404 error in the output as well actually. I believe there are really only 2 spots where this could go haywire, line 11 and 13 but it looks correct to me. If I replace the variables with fixed addresses (not user generated) it works fine. Thanks for your help.
import socket
site= raw_input("Enter url:")
print ""
print "site is",site
print ""
hostel = site.split("/")
print "Hostel is", hostel
print ""
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((hostel[2], 80))
mysock.send('GET site HTTP/1.0\n\n')
while True:
data = mysock.recv(1024)
data = data.strip()
if len(data) < 1:
break
print data
mysock.close()
You're not using your site variable here, but literally requesting "site":
mysock.send('GET site HTTP/1.0\n\n')
Try:
mysock.send('GET ' + site + ' HTTP/1.0\n\n')
You should use the variable 'site' instead of the word site try:
message_send = "GET / HTTP/1.1\r\nHost: %s\r\n\r\n".format(site)
mysock.send(message_send)

Python telnet connection refuse exception

I'm using following function to make telnet connection verification
telnetlib.Telnet("172.28.5.240", "8080")
When the connection refused it shows exception message. Is it possible to hide the message and detect as success or failed through if condition?
You can use try-except-finally blocks
try:
#
#
response = 'Success'
except:
response = 'Failed'
finally:
print response
Based on Suku's answer I develop my code. that is a working answer. And following is my script for reference.
try:
conn = telnetlib.Telnet("172.28.5.240", "80")
response = 'Success'
except:
response = 'Failed'
finally:
print response
None of the options helped me.
Maybe someone will come in handy.
100% working version:
Used to check the availability of the RDP server in ZABBIX:
import telnetlib
response = ''
HOST = '192.168.1.201'
PORT = 3389
tn = telnetlib.Telnet()
try:
tn.open(HOST, PORT, 3)
response = '2'
except Exception:
response = '0'
finally:
tn.close()
print(response)

Web Server: socket programming for TCP connections in Python

I'm trying to run a python web server. The server says is running so I assume it is all working, except that I can only see the html text. The jpeg/image and the pdf files won't dispaly. Here is what i have so far.
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', 12000))
serverSocket.listen(1)
while True:
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print 'Required connection', addr
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Fill in start
connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill in start
connectionSocket.send('404 Not Found')
#Fill in end
#Close client socket
#Fill in start
connectionSocket.close()
#Fill in end
serverSocket.close()
I'm working on the same thing. I added the line:
connectionSocket.send('Content-Type: image/jpeg')
right after this:
connectionSocket.send('HTTP/1.0 200 OK')
I assume I'm/we're just missing some line in the header.