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)'),))",),))
Related
I am uploading an image file to the server but when timeout occurs it terminates the upload and move to the next. i want to upload the image again if timeout occurs. I want to try to upload three times at max.and after three attempts if still timeout occurs then throw an exception and move to the next.
here's my code
def upload(filename2,sampleFile,curr_time,curr_day,username,password,user_id):
register_openers()
datagen, headers = multipart_encode({"sampleFile": open(sampleFile), "name": filename2, "userID": user_id,'date': curr_day,'time': curr_time, 'username': username,'password': password})
request = urllib2.Request("http://videoupload.hopto.org:5001/api/Synclog", datagen, headers)
try:
response = urllib2.urlopen(request, timeout = 20)
html=response.read()
except URLError , e:
if hasattr(e, 'reason'):
print ('Reason: ', e.reason)
elif hasattr(e, 'code'):
print ('Error code: ', e.code)
except Exception:
print ('generic exception: ' + traceback.format_exc())
return
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()
I run this code:
import requests
loginurl = 'https://auth.cbssports.com/login/index'
try:
response = requests.get(loginurl)
except requests.exceptions.ConnectionError as e:
print "Login URL is BAD"
response = requests.get(loginurl)
It consistently returns this error:
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='auth.cbssports.com', port=443): Max retries exceeded with url: /login/index (Caused by <class 'socket.error'>: [Errno 10054] An existing connection was forcibly closed by the remote host)
I am able to access this url manually. I can't figure out why Python can't. Is there a way to solve this?
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)
Ok, I've tried to resolve this with a couple of different libraries. I'm working on a script to look at thousands of sites and kick out specific items on the pages. I need to be able to reset the connection so that the script will continue without losing any data. I've tried catching the error and waiting but that doesn't seem to fix it as it eventually causes the script to error completely out. I get the error on the below snippet of code in my status check module.
def status(url): #checks the response code
try:
req=urllib2.urlopen(url)
response=req.getcode()
return response
except urllib2.HTTPError, e:
return e.code
print e.code
except urllib2.URLError, e:
print e.args
return e.args
But before trying this I used the below as instead of urrlib2
parsedurl = urlparse(url)
conn = httplib.HTTPConnection(parsedurl.netloc)
conn.request('HEAD',parsedurl.path)
response = conn.getresponse()
return response.status