How to see traceback on xmlrpc server, not client? - python

I have simple xmlrpc server code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
port = 9999
def func():
print 'Hi!'
print x # error!
print 'Bye!'
if __name__ == '__main__':
server = SimpleXMLRPCServer(("localhost", port))
print "Listening on port %s..." % port
server.register_function(func)
server.serve_forever()
Sample session.
Client:
>>> import xmlrpclib
>>> p = xmlrpclib.ServerProxy('http://localhost:9999')
>>> p.func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\xmlrpclib.py", line 1199, in __call__
return self.__send(self.__name, args)
File "C:\Python26\lib\xmlrpclib.py", line 1489, in __request
verbose=self.__verbose
File "C:\Python26\lib\xmlrpclib.py", line 1253, in request
return self._parse_response(h.getfile(), sock)
File "C:\Python26\lib\xmlrpclib.py", line 1392, in _parse_response
return u.close()
File "C:\Python26\lib\xmlrpclib.py", line 838, in close
raise Fault(**self._stack[0])
xmlrpclib.Fault: <Fault 1: "<type 'exceptions.NameError'>:global name 'x' is not defined">
>>>
Server:
Listening on port 9999...
Hi!
localhost - - [11/Jan/2011 16:17:09] "POST /RPC2 HTTP/1.0" 200 -
The question is if I can get this trace back also on server. I need to know if something went wrong with processing query. I'm not using client written in Python so it is hard for me to get traceback like above.

You can do something like this:
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
port = 9999
def func():
print 'Hi!'
print x # error!
print 'Bye!'
class Handler(SimpleXMLRPCRequestHandler):
def _dispatch(self, method, params):
try:
return self.server.funcs[method](*params)
except:
import traceback
traceback.print_exc()
raise
if __name__ == '__main__':
server = SimpleXMLRPCServer(("localhost", port), Handler)
server.register_function(func)
print "Listening on port %s..." % port
server.serve_forever()
Traceback server side:
Listening on port 9999...
Hi!
Traceback (most recent call last):
File "xml.py", line 13, in _dispatch
value = self.server.funcs[method](*params)
File "xml.py", line 7, in func
print x # error!
NameError: global name 'x' is not defined
localhost - - [11/Jan/2011 17:13:16] "POST /RPC2 HTTP/1.0" 200

Related

Onion Server with Stem and CherryPy in Python

I want to create an Onion-Website with CherryPy in Python (using Stem to access the Tor network). My problem is the deployment of the site. For that I adopted the example from this article: https://jordan-wright.com/blog/2014/10/06/creating-tor-hidden-services-with-python/ (great article, but originally in combination with Flask, but this should also work with CherryPy and vice versa). Only difference is that Flask operates on port 5000 and CherryPy on 8080 (I changed that in the code below).
My final test-code looks like this:
import cherrypy
from stem.control import Controller
class HelloWorld(object):
#cherrypy.expose
def index(self):
return "Hello world!"
if __name__ == '__main__':
port = 8080
host = "127.0.0.1"
hidden_svc_dir = '/home/python/'
print(" * Getting controller")
controller = Controller.from_port(address="127.0.0.1", port=9151)
try:
controller.authenticate(password="")
controller.set_options([
("HiddenServiceDir", hidden_svc_dir),
("HiddenServicePort", "80 %s:%s" % (host, str(port)))
])
svc_name = open(hidden_svc_dir + "/hostname", "r").read().strip()
print(" * Created host: %s" % svc_name)
except Exception as e:
print(e)
cherrypy.quickstart(HelloWorld())
My /etc/tor/torrc contains this:
ControlPort 9051
HashedControlPassword xxx
CookieAuthentication 1
(I also tried with/without Password and with/without Cookies set to 1 and 0 - all with the same error message.)
Though in other codes I use Stem / Tor and they work properly, this one throws the folling error message:
* Getting controller
Traceback (most recent call last):
File "/home/xxx/.local/lib/python3.6/site-packages/stem/socket.py", line 535, in _make_socket
control_socket.connect((self.address, self.port))
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "onion_server_1.py", line 20, in <module>
controller = Controller.from_port(address="127.0.0.1", port=9151)
File "/home/xxx/.local/lib/python3.6/site-packages/stem/control.py", line 1033, in from_port
control_port = stem.socket.ControlPort(address, port)
File "/home/xxx/.local/lib/python3.6/site-packages/stem/socket.py", line 503, in __init__
self.connect()
File "/home/xxx/.local/lib/python3.6/site-packages/stem/socket.py", line 172, in connect
self._socket = self._make_socket()
File "/home/xxx/.local/lib/python3.6/site-packages/stem/socket.py", line 538, in _make_socket
raise stem.SocketError(exc)
stem.SocketError: [Errno 111] Connection refused
I have no more ideas why this does not work.
A working code (adopted from mine above) would be great.

Exception happened during processing of request from [duplicate]

This question already has answers here:
Python sockets error TypeError: a bytes-like object is required, not 'str' with send function
(4 answers)
Closed 5 years ago.
here is my code I want to open a server on the localhost:8080.
from http.server import BaseHTTPRequestHandler, HTTPServer
class WebServerHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith("/hi"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message)
print (message)
return
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), WebServerHandler)
print ("Web Server running on port %s" % port)
server.serve_forever()
except KeyboardInterrupt:
print (" ^C entered, stopping web server....")
server.socket.close()
if __name__ == '__main__':
main()
And when i'm open the server i'm supposed to get a white web page with the word "Hello!" wrote on it.
But when i open the page i have a white page and on my terminal i have this :
Exception happened during processing of request from ('10.0.2.2',49701)
Traceback (most recent call last):
File "/usr/lib/python3.5/socketserver.py", line 313, in
_handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 341, in
process_request
self.finish_request(request, client_address)
File "/usr/lib/python3.5/socketserver.py", line 354, in
finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.5/socketserver.py", line 681, in __init__
self.handle()
File "/usr/lib/python3.5/http/server.py", line 422, in handle
self.handle_one_request()
File "/usr/lib/python3.5/http/server.py", line 410, in
handle_one_request
method()
File "webserver.py", line 14, in do_GET
self.wfile.write(message)
File "/usr/lib/python3.5/socket.py", line 593, in write
return self._sock.send(b)
TypeError: a bytes-like object is required, not 'str'
Issue is with this self.wfile.write(message) line
from http.server import BaseHTTPRequestHandler, HTTPServer
class WebServerHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith("/hi"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message.encode('utf-8'))
print (message)
return
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), WebServerHandler)
print ("Web Server running on port %s" % port)
server.serve_forever()
except KeyboardInterrupt:
print (" ^C entered, stopping web server....")
server.socket.close()
if __name__ == '__main__':
main()

errno 111 connection refused with python in ubuntu vmware

Hi I have a problem in my server- client connection
I wrote the 2 codes on windows 10 and they worked perfectly. But when I tried to execute them on ubuntu in a VM I had this error:
Traceback (most recent call last):
File "client3.py", line 9, in <module>
sock.connect(('192.168.1.53', 1234))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
the server code:
import threading
import SocketServer
import json
import base64
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(327680)
data = json.loads(data)
cur_thread = threading.current_thread()
JL= data['Jliste']
for i in range(0,9) :
cel = json.loads(JL[i])
file_name = cel['name']
img = base64.b64decode(cel['img'])
with open(file_name,'wb') as _file:
_file.write(img)
print "image {} Received ".format(i)
response = "images Received "
print response
self.request.sendall(response)
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
server = ThreadedTCPServer(("localhost", 1234), ThreadedTCPRequestHandler)
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print "Server loop running in thread:", server_thread.name
the client code:
import socket
import json
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 1234))
try:
def generate_names(count):
return 'User.2.{}.jpg'.format(count)
L = []
for i in range(0,9):
name = generate_names(i+1)
fp = open(name,'rb')
fp = fp.read()
fp = fp.encode('base64')
cel = {}
cel['name'] = name
cel['img'] = fp
jcel = json.dumps(cel)
L.append(jcel)
data = {}
data['Jliste'] = L
s = json.dumps(data)
sock.send(s)
response = sock.recv(1024)
print "Received: {}".format(response)
finally:
sock.close()
the new error i get is:
Exception happened during processing of request from ('127.0.0.1', 60900)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 596, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 652, in __init__
self.handle()
File "server.py", line 12, in handle
data = json.loads(data)
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 380, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Unterminated string starting at: line 1 column 16913 (char 16912)
Not sure why this works on Windows, but when I run your code on Ubuntu, your server just exits - just as it is supposed to. It prints "server loop running..." and then exits. As your thread is set to server_thread.daemon=True, the thread is killed as well. It does not even have time to initialise the socket.
If you change server_thread.daemon=False or add sleep(600) or something like that (you would of course an infinite loop) as the last statement in your main(), it starts listening to the socket and process requests - which is probably what you want.

Autobahn Python Errno 99 cannot assign requested address

While trying to set up a Websocket server, I have encountered the following error.
The same code works fine under LAN IP '192.168.x.x', but fails to work with a public ip/domain name
Here is the error trace
Traceback (most recent call last):
File "WSServer.py", line 19, in <module>
server = loop.run_until_complete(coro)
File "/usr/lib64/python3.4/asyncio/base_events.py", line 208, in run_until_complete
return future.result()
File "/usr/lib64/python3.4/asyncio/futures.py", line 243, in result
raise self._exception
File "/usr/lib64/python3.4/asyncio/tasks.py", line 319, in _step
result = coro.send(value)
File "/usr/lib64/python3.4/asyncio/base_events.py", line 579, in create_server
% (sa, err.strerror.lower()))
OSError: [Errno 99] error while attempting to bind on address ('121.6.x.x', 9000): cannot assign requested address
Python Server Code:
from autobahn.asyncio.websocket import WebSocketServerProtocol
class MyServerProtocol(WebSocketServerProtocol):
def onMessage(self, payload, isBinary):
print("message received")
self.sendMessage(payload, isBinary)
if __name__ == '__main__':
import asyncio
from autobahn.asyncio.websocket import WebSocketServerFactory
factory = WebSocketServerFactory()
factory.protocol = MyServerProtocol
loop = asyncio.get_event_loop()
coro = loop.create_server(factory, '121.6.x.x', 9000)
server = loop.run_until_complete(coro)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
server.close()
loop.close()
Could the issue be related with the server setting? e.g. hostname, SELinux

web connection with python

I have this code to create a webapp in my server:
import web
urls = (
'/update', 'Update',
)
app = web.application(urls, globals())
class Update:
print "hola"
if __name__=='__main__':
app.run()
When I try to execute:
python#ubuntu:~$ python prueba.py 8081
hola
http://0.0.0.0:8081/
Traceback (most recent call last):
File "prueba.py", line 21, in <module>
app.run()
File "/usr/local/lib/python2.6/dist-packages/web/application.py", line 311, in run
return wsgi.runwsgi(self.wsgifunc(*middleware))
File "/usr/local/lib/python2.6/dist-packages/web/wsgi.py", line 54, in runwsgi
return httpserver.runsimple(func, validip(listget(sys.argv, 1, '')))
File "/usr/local/lib/python2.6/dist-packages/web/httpserver.py", line 148, in runsimple
server.start()
File "/usr/local/lib/python2.6/dist-packages/web/wsgiserver/__init__.py", line 1753, in start
raise socket.error(msg)
socket.error: No socket could be created
Why is it happening?
Thank you in advance
The error message says that it couldn't create a listening socket on the specified port. Check if there is already a server running on port 8081.

Categories