Why is this MQTT client example failing? - python

I am trying out MQTT for the first time using Python and the mosquitto library. My client program is below. I'm trying to use the public demo MQTT server at http://www.mqtt-dashboard.com/subscribe. However the client code is failing, see error below. Any ideas on what's going on?
#!/usr/bin/env python
import mosquitto
client = mosquitto.Mosquitto("fredtest", clean_session=True)
client.connect("broker.mqttdashboard.com", 1883)
client.publish("fred.test", "hello world", 1)
client.loop_forever()
Error message:
C:\tmp>python mqttclient.py
Traceback (most recent call last):
File "mqttclient.py", line 6, in
client.connect("broker.mqttdashboard.com", 1883)
File "build\bdist.win-amd64\egg\mosquitto.py", line 582, in connect
File "build\bdist.win-amd64\egg\mosquitto.py", line 657, in reconnect
File "c:\python27\lib\socket.py", line 571, in create_connection
raise err
socket.error: [Errno 10060] A connection attempt failed because the connected pa
rty did not properly respond after a period of time, or established connection f
ailed because connected host has failed to respond

I'm not currently able to connect any client to broker.mqttdashboard.com:1883 - so this probably isn't an issue with your code.
To sanity check, have you tried connected to another broker, such as iot.eclipse.org:1883 ?

Related

python: To test sending logs to Syslog Server

please help me, how to send python script logs to syslog server (syslog-ng product), i have already tried below method.. it has two approaches. one is with 'SysLogHandler' and other is with 'SocketHandler'
import logging
import logging.handlers
import socket
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address=('10.10.11.11', 611), socktype=socket.SOCK_STREAM)
#handler = logging.handlers.SocketHandler('10.10.11.11', 611)
my_logger.addHandler(handler)
my_logger.debug('this is debug')
my_logger.critical('this is critical')
result: for SysLogHandler
[ansible#localhost ~]$ python test.py
Traceback (most recent call last):
File "test.py", line 8, in <module>
handler = logging.handlers.SysLogHandler(address=('10.10.11.11', 611), socktype=socket.SOCK_STREAM)
File "/usr/lib64/python3.6/logging/handlers.py", line 847, in __init__
raise err
File "/usr/lib64/python3.6/logging/handlers.py", line 840, in __init__
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused #THIS IS OK for me since server unreachable.
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/usr/lib64/python3.6/logging/__init__.py", line 1946, in shutdown
h.close()
File "/usr/lib64/python3.6/logging/handlers.py", line 894, in close
self.socket.close()
AttributeError: 'SysLogHandler' object has no attribute 'socket'
result: SocketHandler ==> No output.. i am not sure if it is working or not.
I am not sure what is proper approach to send logs to syslog server via TCP port.. i have used both syslogHandler & SocketHandler.
syslogHandler:
using syslogHandler i am getting ConnectionRefusedError because my remote server is unreachable, probably i will user try..except method.. But i am not sure why i am getting AttributeError: 'SysLogHandler' object has no attribute 'socket'
SocketHandler:
Python logging module handler page says this class is used for sending logs to remote via TCP.. But i cant see any output, and not sure whether this is correct approach for sending logs to syslog server.
please help..
thanks in advance.
This is not a proper solution, If it's not absolutely necessary to use TCP, I would advise you to use UDP. it solved a lot of my issues with syslog handler. TCP seemed to want to bundle messages together and ironically it lost some messages in the batching process.
When i tried this on my computer with a syslog server that is up and listening to port 611, it didn't raise an AttributeError on SysLogHandler. so you should probably set up a server to listen on that port to fix that

Receive data from a client/server doesn't work

I developed a small Python program which should receive and output data from another client or server. However, I get an error message which is unknown to me. Can anyone help me? Thanks a lot
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.1.34', 80))
from_server = client.recv(4096)
client.close()
print from_server
Error:
Traceback (most recent call last):
File "CallManager2.py", line 4, in <module>
client.connect(('192.168.1.34', 80))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
The error comes from inability for your program to reach the server or other client.
Check that there is something listening to incoming connexions on the address you want to connect to.
Then you can check that the address you want to connect to is on the same network as your program.

asyncio fails to connect to RabbitMQ

I'm learning thenextquant quant framework, but always get connection error while connecting to RabbitMQ. after some troubleshooting, i found asynico/aioamqp module always prompts error:An open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.
while trying to connect to RabbitMQ server, RabbitMQ is up and running and other client can connect to it without any error.
Then I followed the hello world example from aioamqp(https://github.com/Polyconseil/aioamqp/blob/master/examples/send.py) to write a test program, then reproduced the error.
import asyncio
import aioamqp
async def send():
transport, protocol = await aioamqp.connect(host="127.0.0.1", port=5672, login="guest", password="guest", login_method="PLAIN")
channel = await protocol.channel()
await channel.queue_declare(queue_name='hello')
await channel.basic_publish(
payload='Hello World!',
exchange_name='',
routing_key='hello'
)
print(" [x] Sent 'Hello World!'")
await protocol.close()
transport.close()
asyncio.get_event_loop().run_until_complete(send())
(venv_380) appledeMBP:Market apple$ python hello.py
An open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly.
Traceback (most recent call last):
File "hello.py", line 31, in <module>
asyncio.get_event_loop().run_until_complete(send())
File "/Users/apple/.pyenv/versions/3.8.0/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
return future.result()
File "hello.py", line 14, in send
transport, protocol = await aioamqp.connect(host="127.0.0.1", port=5672, login="guest", password="guest", login_method="PLAIN")
File "/Users/apple/.virtualenvs/venv_380/lib/python3.8/site-packages/aioamqp/__init__.py", line 59, in connect
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
File "/Users/apple/.pyenv/versions/3.8.0/lib/python3.8/asyncio/trsock.py", line 82, in setsockopt
self._sock.setsockopt(*args, **kwargs)
OSError: [Errno 9] Bad file descriptor
finally I found it's caused by version of Python. the issue is gone once using 3.6 instead of 3.8 which result in connection issue with aioamqp.connect()

Slack bot rtm connect fails behind proxy, using python slackclient

When running slack bot using proxies SlackClient.rtm_connect() fails with below error, where as at the same time api_calls api.test, auth.test seems working fine, any idea how this can be fixed ? Am i missing some other configuration ?
WARNING:slackclient.client:Failed RTM connect
Connection failed. Exception traceback printed above.
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\slackclient\client.py", line 140, in rtm_connect
self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs)
File "C:\Python27\lib\site-packages\slackclient\server.py", line 159, in rtm_connect
self.connect_slack_websocket(self.ws_url)
File "C:\Python27\lib\site-packages\slackclient\server.py", line 200, in connect_slack_websocket
raise SlackConnectionError(message=str(e))
SlackConnectionError: [Errno 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
Below is the code snippet,
from slackclient import SlackClient
client_proxies = {"https": "https://127.0.0.1:8080"}
slack_client = SlackClient(token=BOT_TOKEN, proxies=client_proxies)
print slack_client.api_call("api.test")
print slack_client.api_call("auth.test")
slack_client.rtm_connect()
api_call api.test returned below
{u'token': u'TOKEN'}, u'ok': True}

Error 2003 Can't connect to MySQL server on 'localhost' PyMySQL

I'm not really sure what to do here. I'm trying to connect to MySQL Community Server by using a python script, and I'm running into an error message. This is being run on OS X Yosemite. I'm using the PyMySQL module, which imports correctly. The line
con = pms.connect(host='localhost',user='jaxon',passwd='password')
throws the following error message:
Traceback (most recent call last):
File "/Users/icefreak21/Documents/Python Files/DBConnector.py", line 4, in <module>
con = pms.connect(host='127.0.0.1',user='root',passwd='c0c0_puFF')
File "/Users/icefreak21/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/Users/icefreak21/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pymysql/connections.py", line 644, in __init__
self._connect()
File "/Users/icefreak21/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pymysql/connections.py", line 869, in _connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 61] Connection refused)")
I've searched around on the site and haven't found a question that details this particular situation. As far as I can tell, the server is running; the kicker is that I have no problem connecting through the command line with the same host, user, and password. I've tried switching the host name to '127.0.0.1' and I've tried specifying the port number (3306).
I found one solution that suggested specifying the socket, but when I ran the suggested code
./mysqladmin variables | grep socket
to find the socket file to specify, I get the following error code:
./mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'jaxon'#'localhost' (using password: NO)'
Does anyone have any other suggestions?
I had the same problem. I solved it by changing the port. You can add your port like this:
3307(port = 3307)
I'm recommending this because the mysql port of mac vision might be 3307.

Categories