Python telnet connection refuse exception - python-2.7

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)

Related

Getting 404 error for every page with python socket

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

pysftp gives pysftp.exceptions.ConnectionException: (host, port) with no details on it

I'm trying to connect to sftp server with pysftp library. Here is my code:
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection("sftp://host", "login", "password", cnopts=cnopts) as sftp:
sftp.listdir()
It gives me exception:
pysftp.exceptions.ConnectionException: ('host', port)
But I have no clue what this exception means and what the problem is.
You don't have much explanation because this library has bugs. See the source code on BitBucket.
The ConnectionException class is not well implemented:
class ConnectionException(Exception):
"""Exception raised for connection problems
Attributes:
message -- explanation of the error
"""
def __init__(self, host, port):
# Call the base class constructor with the parameters it needs
Exception.__init__(self, host, port)
self.message = 'Could not connect to host:port. %s:%s'
As you can see, the format 'Could not connect to host:port. %s:%s' is not filled with the host and port values.
However, the name of the exception is clear: you have a connection error.
The details of the error are, unfortunately, lost:
def _start_transport(self, host, port):
'''start the transport and set the ciphers if specified.'''
try:
self._transport = paramiko.Transport((host, port))
# Set security ciphers if set
if self._cnopts.ciphers is not None:
ciphers = self._cnopts.ciphers
self._transport.get_security_options().ciphers = ciphers
except (AttributeError, socket.gaierror):
# couldn't connect
raise ConnectionException(host, port)
You can try to get the last error (not sure):
import sys
sys.exc_info()
note: I suggest you to use another library (for instance Paramiko).

Why does the Python script to send data to Slack web hook not work when variable is pulled from a line?

Language: Python 2.7
Hello all. I found a really helpful script here: Python to Slack Web Hook
that shows how to send messages to a Slack web hook.
import json
import requests
# Set the webhook_url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/
webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
slack_data = {"text": "<https://alert-system.com/alerts/1234|Click here> for details!"}
response = requests.post(
webhook_url, data=json.dumps(slack_data),
headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
raise ValueError(
'Request to slack returned an error %s, the response is:\n%s'
% (response.status_code, response.text)
)
It works flawlessly when I run .py file.
Now, I have a file that has many lines of messages that I want to send to Slack. I have it formatted correctly already in the file, no spaces etc.. It's just a matter of grabbing it and passing it so slack_data = line1 etc..
So, I modify the file with something like this:
with open('export.txt', 'r') as e:
for line in e:
slack_data = line
Now if I do a print slack_data right after that, the information returns on the screen exactly as it should be, so I'm thinking it's good. I haven't began to get it working for each line yet, because it's not even working on the first line.
I get an invalid payload 400 when I run it.
EDIT: Slack support said the what they were receiving has escape characters inserted into for some reason.
"{\"text\": \"<https://alert-system.com/alerts/1234|Click here> for details!"}\n"
Any direction or assistance is appreciated.
Thanks!!
Just posting as it might help somebody. For me the below snippet worked:
data = json.dumps(slack_data)
response = requests.post(
URL, json={"text": data},
headers={'Content-Type': 'application/json'}
)
As #Geo pointed out the final payload that we are going to send should have keyword "text", else it will fail.
Moreover, in post method I have to replace data= with json= else it kept throwing error for invalid payload with 400
Since I already had the data preformatted in the file as JSON already, it was just a matter of removing json.dumps out of the code.
OLD:
#response = requests.post(webhook_url, data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
NEW:
response = requests.post(webhook_url, data=slack_data, headers={'Content-Type': 'application/json'})
Once I did that, everything worked like a charm.
If you change the code to this:
with open('export.txt', 'r') as e:
slack_data = e.read()
do you still get the 400?

Python: Accessing HTTPS url over Proxy using Requests

import shutil
import requests
import json
proxy = {
'user' : 'user',
'pass' : 'password',
'host' : "test.net",
'port' : 8080
}
url = 'https://github.com/timeline.json'
response = requests.get(url,verify=True, proxies={"https" : \
"http://%(user)s:%(pass)s#%(host)s:%(port)d" % proxy})
with open(r'..\test.json','wb') as out_file:
out_file.write(response.text)
print response
I'm trying to access a HTTPS link (e.g https://github.com/timeline.json) over proxy in office environment using Requests.
Accessing HTTP link seems to be working fine. Getting SSL error in HTTPS.
Please suggest what's missing in the code. Thanks!
Error received:
raise SSLError(e)
requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol
I am using almost the same code you provided, and searched an proxy server. Everything is OK with me.
Try to take a look at document here requests proxies. And notice that https://github.com/timeline.json is deprecated by Github,try https://api.github.com/events
According to doc:
To use HTTP Basic Auth with your proxy, use the http://user:password#host/ syntax:
proxies = {
"http": "http://user:pass#10.10.1.10:3128/",
}
Are you missing a / at the end? Take a try.
import requests
url = 'https://api.github.com/events'
proxy = {
"http" : "http://211.162.xxx.xxx:80"
}
response = requests.get(url, verify=True, proxies=proxy)
print response.status_code
if response.status_code == requests.codes.ok:
response.encoding = 'utf-8'
jsontxt = response.json()
print jsontxt

errno 10054 on Status check request

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