How to catch socket timeout in Python 3? - python

Part of my script:
def testConnection(self):
# This code doesn't work
try:
self.imap.login(self.user, self.password)
return True
except:
return False
When I try to connect with imaplib to mail server with wrong settings, script always crashes with this error:
Traceback (most recent call last):
File "./mail-notifier.py", line 198, in <module>
mail_check()
File "./mail-notifier.py", line 161, in mail_check
if (SettingsExist() == True and Mail().testConnection() == True):
File "./mail-notifier.py", line 142, in __init__
self.imap = imaplib.IMAP4_SSL(settings.value("MailServer"), settings.value("Port"))
File "/usr/lib64/python3.4/imaplib.py", line 1221, in __init__
IMAP4.__init__(self, host, port)
File "/usr/lib64/python3.4/imaplib.py", line 181, in __init__
self.open(host, port)
File "/usr/lib64/python3.4/imaplib.py", line 1234, in open
IMAP4.open(self, host, port)
File "/usr/lib64/python3.4/imaplib.py", line 257, in open
self.sock = self._create_socket()
File "/usr/lib64/python3.4/imaplib.py", line 1224, in _create_socket
sock = IMAP4._create_socket(self)
File "/usr/lib64/python3.4/imaplib.py", line 247, in _create_socket
return socket.create_connection((self.host, self.port))
File "/usr/lib64/python3.4/socket.py", line 512, in create_connection
raise err
File "/usr/lib64/python3.4/socket.py", line 503, in create_connection
sock.connect(sa)
socket.timeout: timed out
I can't catch timeout exception and print error message and continue to work. I thought " except: " catches all errors that happen. I tried to set " except socket.timeout: " but unsuccessfully. What did I wrong?

socket.connect(address)
Connect to a remote socket at address. (The format of address depends on the address family — see above.)
If the connection is interrupted by a signal, the method waits until the connection completes, or raise a socket.timeout on timeout, if the signal handler doesn’t raise an exception and the socket is blocking or has a timeout. For non-blocking sockets, the method raises an InterruptedError exception if the connection is interrupted by a signal (or the exception raised by the signal handler).
Changed in version 3.5: The method now waits until the connection completes instead of raising an InterruptedError exception if the connection is interrupted by a signal, the signal handler doesn’t raise an exception and the socket is blocking or has a timeout (see the PEP 475 for the rationale).
In case of remote connection you should check if the Internet connection can be established (you and remote destination are reachable) and connection setting to perform actions you want are correct.

Related

ConnectionRefusedError: [Errno 111] Connection refused - MQTT.connect()

I would like some ideas please to catch the error below.
I know what caused the error - I stopped the mosquitto service.
This is a test case because in the real world the broker is on another machine (controlled by HomeAssistant)
In the case of an overall restart / power failure etc there is no guarantee what order devices restart in.
I would like this slave to quietly retry until everything is OK.
I was hoping it could be controlled in the on_connect callback but it never gets that far
it is crashing on the 'G_mqtt_client.connect' call
Traceback (most recent call last):
File "/home/pi/Documents/Code/watering_ctrl_1v00.py", line 382, in <module>
mqtt_initialisation()
File "/home/pi/Documents/Code/watering_ctrl_1v00.py", line 202, in mqtt_initialisation
G_mqtt_client.connect(params.G_broker_url, params.G_broker_port)
File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 914, in connect
return self.reconnect()
File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 1044, in reconnect
sock = self._create_socket_connection()
File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 3685, in _create_socket_connection
return socket.create_connection(addr, timeout=self._connect_timeout, source_address=source)
File "/usr/lib/python3.9/socket.py", line 843, in create_connection
raise err
File "/usr/lib/python3.9/socket.py", line 831, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
relevant part of my code
def mqtt_initialisation():
mod = '(messaging.initialisation) '
## establish callback routines - actions to take when events occur
G_mqtt_client.on_connect = on_mqtt_connect
G_mqtt_client.on_disconnect = on_mqtt_disconnect
G_mqtt_client.on_message = message_received
G_mqtt_client.on_log = on_mqtt_log
G_mqtt_client.username_pw_set(params.G_broker_user, params.G_broker_pwd)
G_mqtt_client.connect(params.G_broker_url, params.G_broker_port)
G_mqtt_client.loop_start()
main_log.debug(mod + "after Mqtt client loop start")
def on_mqtt_connect(client, userdata, flags, rc):
main_log.info("MQTT Connected With Result Code " + str(rc)) ## happens at start and if re-connected
do_subscribe()
def on_mqtt_disconnect(client, userdata, rc):
main_log.info("MQTT Client Got Disconnected") ## this appears if, say, mosquitto goes offline
def on_mqtt_log(client, userdata, level, buff):
main_log.info("MQTT Client error ...")
main_log.info(buff)

Getting timeout error while using smtplib library to send email

Here is my code:
import smtplib
connection = smtplib.SMTP("smtp.gmail.com")
connection.starttls()
connection.login(user="mymail#gmail.com", password="mypassowrd")
connection.sendmail(from_addr="mymail#gmail.com", to_addrs="recievermail#gmail.com", msg="Hello")
connection.close()
So I am getting this error:
Traceback (most recent call last):
File "E:\100Days-Python_programs\Day32\Birthday Wisher (Day 32) start\main.py", line 3, in <module>
connection = smtplib.SMTP("smtp.gmail.com")
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 253, in __init__
(code, msg) = self.connect(host, port)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 339, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 310, in _get_socket
return socket.create_connection((host, port), timeout,
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\socket.py", line 843, in create_connection
raise err
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\socket.py", line 831, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Process finished with exit code 1
I turned on Less secure app access:
I turned off every security steps too:
And I also turned off the firewall protection as well.
But Nothing worked.
So please someone help me.
You need to specify the port. In this case, it's 587 for TSL.
Somehow it works, but I don't have profound knowledge to explain why.
I had the same problem, so there is a solution:
connection = smtplib.SMTP("smtp.gmail.com", 587)

Python SSL FTP connection timing out

I'm trying to get a connection established to a FTP server with SSL from within Python (v3.3.0). But I keep getting a timeout. I am NOT using port 990 as the SSL port (paranoid). Would that be the cause of this problem? And if so, how do I specify the port I am using?
Here's my script:
from ftplib import FTP
from ftplib import FTP_TLS
ftps = FTP_TLS('ip address')
ftps.auth()
ftps.sendcmd('USER uname')
ftps.sendcmd('PASS password')
ftps.prot_p()
ftps.retrlines('LIST')
ftps.close()
And here is the result:
Traceback (most recent call last):
File "Scrpit name removed for posting", line 12, in <module>
ftps.retrlines('LIST')
File "C:\Python33\lib\ftplib.py", line 767, in retrlines
conn = self.transfercmd(cmd)
File "C:\Python33\lib\ftplib.py", line 381, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "C:\Python33\lib\ftplib.py", line 742, in ntransfercmd
conn, size = FTP.ntransfercmd(self, cmd, rest)
File "C:\Python33\lib\ftplib.py", line 343, in ntransfercmd
source_address=self.source_address)
File "C:\Python33\lib\socket.py", line 424, in create_connection
raise err
File "C:\Python33\lib\socket.py", line 415, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
any advice would be greatly appreciated,
After looking at the ftplib source, it doesn't seem to want to use any port but 21.
I think you should be able to work around this, something like
import ftplib
ftplib.FTP.port = 995 # or whatever port you are using
ftps = ftplib.FTP_TLS('hostname', 'user', 'pwd')
ftps.retrlines('LIST')
Set the port through the connect
import ftplib
ftps = ftplib.FTP_TLS()
ftps.connect ('hostname', 991)

handling telnetlib timeout error in python

I am trying to write a python script to establish a telnet connection (using telnetlib) to a range of hosts:
for i in range(len(HOST)):
print "scanning " + HOST[i] + " ...\n"
tn = telnetlib.Telnet(HOST[i],23,3)
The problem is when one of the connections times out, the script executions interrupts and returns the following error:
Traceback (most recent call last):
File "C:\Python27\telnet.py", line 24, in <module>
tn = telnetlib.Telnet(HOST[i],23,3)
File "C:\Python27\lib\telnetlib.py", line 209, in __init__
self.open(host, port, timeout)
File "C:\Python27\lib\telnetlib.py", line 225, in open
self.sock = socket.create_connection((host, port), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
socket.timeout: timed out
Anyone knows how to skip this error and continue the script?
You need to use a try...except block to catch the exception and tell the interpreter to ignore it. For example:
import socket
for i in range(len(HOST)):
print "scanning " + HOST[i] + " ...\n"
try:
tn = telnetlib.Telnet(HOST[i],23,3)
except socket.timeout:
pass
In this case it's a good idea to explicitly state which exception you want to catch (socket.timeout). Sockets can throw many different types of exceptions so using a generic except: statement might mask a problem with opening, reading or writing to the socket.

python xmlrpc timeout error

I am using xmlrpc to contact a local server. On the client side, Sometimes the following socket timeout error and happens and its not a consistent error.
Why is it happening? What could be the reason for socket timeout?
<class 'socket.timeout'>: timed out
args = ('timed out',)
errno = None
filename = None
message = 'timed out'
strerror = None
Traceback on the server side is as follows
Exception happened during processing of request from ('127.0.0.1', 34855)
Traceback (most recent call last):
File "/usr/lib/python2.4/SocketServer.py", line 222, in handle_request
self.process_request(request, client_address)
File "/usr/lib/python2.4/SocketServer.py", line 241, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.4/SocketServer.py", line 254, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.4/SocketServer.py", line 521, in __init__
self.handle()
File "/usr/lib/python2.4/BaseHTTPServer.py", line 314, in handle
self.handle_one_request()
File "/usr/lib/python2.4/BaseHTTPServer.py", line 308, in handle_one_request
method()
File "/usr/lib/python2.4/SimpleXMLRPCServer.py", line 441, in do_POST
self.send_response(200)
File "/usr/lib/python2.4/BaseHTTPServer.py", line 367, in send_response
self.send_header('Server', self.version_string())
File "/usr/lib/python2.4/BaseHTTPServer.py", line 373, in send_header
self.wfile.write("%s: %s\r\n" % (keyword, value))
File "/usr/lib/python2.4/socket.py", line 256, in write
self.flush()
File "/usr/lib/python2.4/socket.py", line 243, in flush
self._sock.sendall(buffer)
error: (32, 'Broken pipe')
I killed the server and restarted it. Its working fine now.
What could be the reason?
My machine's RAM went full yesterday night by a process and came back to normal today morning.
Will this error be because of some swapping of processes?
Looks like the client socket it timing out waiting for the server to respond. Is it possible that your server might take a lot time to respond some times? Also, if the server is causing the machine to go into swap, that would slow it down making a timeout possible.
If I remember right, socket timeout is not set in xmlrpc in python. Are you doing socket.setdefaulttimeout somewhere in your code?
If it is expected that your server will take time once in a while, then you could set a higher timeout value using above.
HTH

Categories

Resources