Trying to send data into a RabbitMQ queue using Python.
I haven't configured the server but it is running for other processes. I have a working login and can access the web output without problem.
The example code RabbitMQ gives for python uses Pika:
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='xxx.xxx.xxx.xxx:xxxxx'))
channel = connection.channel()
channel.queue_declare(queue='Test')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
This runs and kicks me off with:
pika.exceptions.ConnectionClosed
Not a lot to go on but safe assumption is a login issue because the example code doesn't have any login info.
So I added it.
import pika
import sys
try:
credentials = pika.PlainCredentials('username', 'password')
connection = pika.BlockingConnection(pika.ConnectionParameters('xxx.xxx.xxx.xxx',
xxxxx,
'virtualhostnamehere',
credentials,))
channel = connection.channel()
channel.queue_declare(queue='Test')
channel.basic_publish(exchange='amq.direct',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
except:
e = sys.exc_info()[0]
print e
It seems to hang around for a good few minutes before giving me:
<class 'pika.exceptions.IncompatibleProtocolError'>
The server is running other services fine but I can't seem to pinpoint what I've done wrong.
The login is correct. The vhost name is correct. The host is correct. the exchange name is correct.
Would appreciate a point in the right direction.
Update:
I've tried using URLParameters as well with the same results.
parameters = pika.URLParameters('amqp://username:password#xxx.xxx.xxx.xxx:xxxxx/notmyvhostname')
connection = pika.BlockingConnection(parameters)
But I guess the port doesn't change anything. It's port 15672 and the
login is the same as I used to get on the browser output.
Use port 5672 - or whichever default port you have setup for AMQP listener. Port 15672 is for web UI access, which is done over HTTP, hence the incompatible protocol error
Related
This question already has an answer here:
aiosmtpd - python smtp server
(1 answer)
Closed 3 months ago.
I had "successfully" made an SMTP server. The code works fine connecting to SMTP clients. But it is neither able to recieve emails nor send it. I tried with various test servers and also the standard gmail/yahoo etc.
Here is the code:
# Copyright 2014-2021 The aiosmtpd Developers
# SPDX-License-Identifier: Apache-2.0
import asyncio
from asyncio.base_events import Server
import logging
import aiosmtpd
from aiosmtpd.controller import DEFAULT_READY_TIMEOUT, Controller
import ssl
from aiosmtpd.smtp import Envelope, Session
from smtplib import SMTP as SMTPCLient
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain('cert.pem', 'privkey.pem')
class ExampleHandler():
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
if address.endswith('#example.com'):
print('not relaying to that domain bro :(')
return '550 not relaying to that domain'
envelope.rcpt_tos.append(address)
print(address+" "+"is added to rcpt_tos")
# Make an envelope for the recipient with the same content.
return '250 OK'
# async def handle_EHLO(self, server, session, envelope):
# print('EHLO from %s' % envelope.mail_from)
# return '250-Hello, how are you?\n250-I am fine\n250 HELP'
async def handle_DATA(self, server, session, envelope):
print('Message from %s' % envelope.mail_from)
print('Message for %s' % envelope.rcpt_tos)
print('Message data:\n')
for ln in envelope.content.decode('utf8', errors='replace').splitlines():
print(f'> {ln}'.strip())
print()
print('End of message')
# Dump the contents of envelope.content to a file.
fi=open('./mailbox/firstletter.txt','w')
fi.write(envelope.content.decode('utf8', errors='replace'))
fi.close()
# print everything in DATA.
# Send the envelope to the recipient.
return '250 Message will be delivered'
#Define Relay server.
async def amain(loop):
cont = Controller(ExampleHandler(),hostname='x.x.x.x', port=25, server_hostname='Galam Limited',ready_timeout=5000)
# Combining ExampleHandler and Controller into a single Controller.
cont.start()
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
loop.create_task(amain(loop=loop))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
You can test the server reachability . I am stuck and spent 2 whole days to no avail. The issue is definetely not connectivity, I put the port 25 open. Made sure there are no external issues with godaddy either. Any help will be appreicated.
Edit:1
A quick peak at the wire shark data shows absolutely no packet is being transmitted to the outside when I run the client script.
Here is the clinet script I used for testing.
from smtplib import SMTP as Client
from aiosmtpd.controller import Controller
class controller:
hostname='192.168.1.33'
port=25
client = Client(controller.hostname, controller.port)
r = client.sendmail('a#galam.in', ['tester#192.168.1.200'], """\
From: Anne Person <anne#galam.in>
To: Bart Person <tester#192.168.1.200>
Subject: A test
Message-ID: <ant>
Hi Bart, this is Anne.
""")
SMTP 250 code means that a successful connection has been established however the remote host you are sending mails to might have categorized the domain the mail is being sent from as not legitimate.
This can happen if your domain is not authenticated/verified.
You can relay your messages through a trusted SMTP service like sendgrid
You can also check if your domain is verified by sending a mail from your service to check-auth#verifier.port25.com. Port25 is an automated tool that verified your DNS records, SPF records etc.
Hope this works for you!
I'm having a lot of difficulty with a very simple task. I'm attempting to set up a socket.io client in node js, which should then communicate with a local socket.io server setup in python (using the python bindings here. The issue I'm having is the server is detecting the client, but the client never seems to receive the 'connect' event. I suspect this is an issue with the way I've deployed the server asynchronously, but I'm really not sure. The code for each file is below:
server.py
import socketio
from aiohttp import web
HOST = '127.0.0.1'
PORT = 10001
# create a Socket.IO server
sio = socketio.AsyncServer(async_mode='aiohttp', logger=True, engineio_logger=True)
app = web.Application()
sio.attach(app)
#sio.on('connect')
def connect(sid, environ):
print('connect ', sid)
if __name__ == '__main__':
web.run_app(app, host=HOST, port=PORT)
client.js
const io = require('socket.io-client');
const HOST = '127.0.0.1';
const PORT = '10001';
const socket = io(`http://${HOST}:${PORT}`);
console.log('Socket instantiated!');
socket.on('connect', () => {
console.log(`socket connected: ${socket.connected}`);
});
The output I would expect is to see the server print out that the client has connected, and then for the client to print out that it has connected too. However, the client never seems to receive the 'connect' event, so never prints anything to the console.
Finally, an example of the server's output is:
Server initialized for aiohttp.
======== Running on http://127.0.0.1:10001 ========
(Press CTRL+C to quit)
1c17586e4c7e49b48abefea2fba460e6: Sending packet OPEN data {'sid': '1c17586e4c7e49b48abefea2fba460e6', 'upgrades': ['websocket'], 'pingTimeout': 60000, 'pingInterval': 25000}
connect 1c17586e4c7e49b48abefea2fba460e6
1c17586e4c7e49b48abefea2fba460e6: Sending packet MESSAGE data 0
While the client's output is annoyingly just
$ node mySocket.js
Socket instantiated!
and then it just hangs doing nothing.
I'm clearly misunderstanding something here, so thank you in advance!
Small update
I quickly tested using the python socketio client, and succesfully got an actual connection, so this should narrow it down to something I've done in the JS client.
Well, I ended up downgrading from socket.io-client 3.00 (did not see there was this major release 3 days ago) back to 2.3.1, and everything started working again! However, based on the lack of issues listed on Github, I'm guessing this is not a bug that is affecting everyone.
I have been having some issues with timeouts while sending messages to EventHub.
import sys
import logging
import datetime
import time
import os
from azure.eventhub import EventHubClient, Sender, EventData
logger = logging.getLogger("azure")
ADDRESS = "xxx"
USER = "xxx"
KEY = "xxx"
ENDPOINT = "xxx"
try:
if not ADDRESS:
raise ValueError("No EventHubs URL supplied.")
# Create Event Hubs client
client = EventHubClient(ADDRESS, username=USER, password=KEY, debug=True)
sender = client.add_sender(partition="0", send_timeout=300, keep_alive=10)
client.run()
try:
start_time = time.time()
for i in range(10000):
print("Sending message: {}".format(i))
message = "Message {}".format(i)
sender.send(EventData(message))
except:
raise
finally:
end_time = time.time()
client.stop()
run_time = end_time - start_time
logger.info("Runtime: {} seconds".format(run_time))
except KeyboardInterrupt:
pass
My context is as follow; i am able to send messages without problem from my personal development computer, from a virtual machine in Azure, and from on premises server1, but when trying to send messages to on premises server2 i receive the error:
azure.eventhub.common.EventHubError: Send failed: Message send failed with result: MessageSendResult.Timeout
I have tried modifying the send_timeout and the keep_alive (even though i dont belive this configurations are to blame) but with no success, my personal guess is that there is something in my on premises server2 that is blocking or interfering with my communication. Firstly, am i changing the timeout value correctly? i have checked the source code of the class here: link but it seems i am doing it right, but i actually belive such property implies the time after the message is in the queue for sending instead of how long we wait for the response of the event. Secondly, is there a way i can validate that the problem relies on the envoiroment of my on premises server2? for example like exploring the network path with traceroute, or dig? The system is a CentOS. Could it be related to new upgrades in the Python SDK? i just saw this other question where it shows that my method for uploading events has been upgraded just the "01/08/2020" maybe is something related to such upgrades(i doubt it)?
Anyhow, any clues would be greatly aprecciated. For now i will be testing on other servers and checking i can manage to change my implementation to the newer version and see if that solves the issue.
It sounds like a networking issue. Try pinging TCP endpoint of your namespace on port 9354 on server2. If firewall is blocking outbound connection to the endpoint, then either you need to fix it or try enabling websockets which can go through 443.
I made a python socket server recently that listens on port 9777 the server is suppose to accept connections and once it does will allow you to send information to the client. The client will then print out whatever it received. However, I found that after I sent some data the server would hang until i reinitialized a new connection. Is there a reason for this and if so how can I prevent it from happening
The code of the server is :
import socket
import sys
host='0.0.0.0'
port=9777
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(10)
c,a=s.accept()
while True:
command=raw_input('[input>] ')
if 'data' in command:
c.send('continue')
data=c.recv(1024)
print data
else:
continue
the code will only send data if the word data is in the string. Here is the code for the client:
import socket
import sys
host='192.168.0.13'
port=9777
while True:
try:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
except:
continue
while True:
d=s.recv(9999)
print d
s.send('received')
My goal is to setup a connection between server and client. I want the server to be able to accept input from a user in a while loop and send the input to the client. The client needs to be able to receive information and when it does it will send a response to the server. Then the user can continue sending data to the server until they decide to terminate the program. However the server keeps hanging after sending data once to the client. Can anyone tell me how I can prevent that?
I try this code in my computer it's work fine , maybe you need to change host='192.168.0.13' to host='localhost'
and host='0.0.0.0' to host='localhost'
look at this picture
and if this problem stay maybe your ip address is the same of other device in the network for that try to run this command ipconfig /renew
I'm trying to create mockup telnet server (for some functional testing of existing code). Right now I only modified server welcome message and I was trying to read this message using client code, but it read method fails on timeout with no additional info. But with pudb debugger enabled it works most of the time...
I'm using virtualenv, with pudb and telnetsrv installed using pip. Python 2.7.12, ubuntu 16.04.
Server code:
import SocketServer
from telnetsrv.threaded import TelnetHandler
class MyHandler(TelnetHandler):
WELCOME = "HI from custom server"
class TelnetServer(SocketServer.TCPServer):
allow_reuse_address = True
server = TelnetServer(("0.0.0.0", 8023), MyHandler)
server.serve_forever()
Client code:
import telnetlib
HOST = '127.0.0.1'
PORT = 8023
# from pudb import set_trace; set_trace()
tn = telnetlib.Telnet(HOST, PORT)
data = tn.read_until("custom server", timeout=1)
print "Data: " + data
tn.close()
Client output:
$ python client.py
Data:
Client output with pudb enabled (with step-by-step execution)
$ python client.py
Data: HI from custom server
Of course when I execute shell telnet command, it all works fine:
$ telnet 127.0.0.1 8023
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
HI from custom server
Telnet Server>
I'd really appreciate any hints on how to debug this problem. Thanks!
Be sure there is actually connecting going on. To do that put edit your code to add tn.set_debuglevel(100) into your script to look like this:
import telnetlib
HOST = '127.0.0.1'
PORT = 8023
# from pudb import set_trace; set_trace()
tn = telnetlib.Telnet(HOST, PORT)
tn.set_debuglevel(100)
data = tn.read_until("custom server", timeout=1)
print "Data: " + data
tn.close()
This will ensure all the data is printed out so you can see what's going on.
My theory is, that you're not connecting, or that your data isn't actually outputting "custom server" and therefor it won't catch it, or your timeout is too low.