How can I save the output from the console like
"192.168.1.1 - - [18/Aug/2014 12:05:59] code 404, message File not found"
to a file?
Here is the code:
import SimpleHTTPServer
import SocketServer
PORT = 1548
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
BaseHTTPRequestHandler.log_message() prints all log messages by writing to sys.stderr. You have two choices:
1) Continue using BaseHTTPRequestHandler.log_message(), but change the value of sys.stderr:
import SimpleHTTPServer
import SocketServer
PORT = 1548
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
import sys
buffer = 1
sys.stderr = open('logfile.txt', 'w', buffer)
httpd.serve_forever()
2) Create a new xxxRequestHandler class, replacing .log_message():
import SimpleHTTPServer
import SocketServer
import sys
PORT = 1548
class MyHTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
buffer = 1
log_file = open('logfile.txt', 'w', buffer)
def log_message(self, format, *args):
self.log_file.write("%s - - [%s] %s\n" %
(self.client_address[0],
self.log_date_time_string(),
format%args))
Handler = MyHTTPHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
I have used BaseHTTPServer instead of SimpleHTTPServer.
There you go:
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
PORT_NUMBER = 5451
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
#self.send_header('Content-type','text/html')
self.end_headers()
text_file = open("ip.txt", "a")
text_file.write(str(self.client_address) + "\n")
text_file.close()
# Send the html message
#self.wfile.write("Hello World !")
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
Related
Below is my script. It creates a directory, detects an arduino device, continuously writes output from it to a text file, and serves that file in a local server. From what I can tell (and have read), this line:
httpd.serve_forever()
causes nothing after to be processed. The text file never get's written to. If I move httpd.serve_forever() line down further, it'll process everything up to that point, so this does appear to reaffirm this theory. How can I do what I need? Is it clear where I'm going wrong?
import serial
import serial.tools.list_ports
import os
import SimpleHTTPServer
import SocketServer
import sys,os
fileDir = os.path.dirname(os.path.realpath('__file__'))
try:
os.makedirs(os.path.join(fileDir, 'log'))
except OSError:
if not os.path.isdir(os.path.join(fileDir, 'log')):
raise
directory = os.path.join(fileDir, 'log')
log = os.path.join(directory, 'log.txt')
os.chdir(directory)
PORT = 8080
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
httpd.serve_forever()
def get_ports():
ports = serial.tools.list_ports.comports()
return ports
def findArduino(portsFound):
commPort = 'None'
numConnection = len(portsFound)
for i in range(0,numConnection):
port = foundPorts[i]
strPort = str(port)
if 'Arduino' in strPort:
splitPort = strPort.split(' ')
commPort = (splitPort[0])
return commPort
foundPorts = get_ports()
connectPort = findArduino(foundPorts)
if connectPort != 'None':
ser = serial.Serial(connectPort,baudrate = 9600, timeout=1)
while 1:
if ser.inWaiting():
with open(log, "w") as txtfile:
x=ser.readline()
txtfile.write(x)
txtfile.flush()
if x=="\n":
txtfile.seek(0)
txtfile.truncate
txtfile.flush()
ser.close()
else:
print('Connection Issue!')
print('DONE')
I am new to python and i am trying to make a multithreded tcp server and client to be able to send files between them. I did write some simple codes for these two programs but every time I get empty file on server's site. The file does create in the folder but when I open it it is blank inside. I also tried to send .png files but windows photoviewer doesn't open them saying they are empty. I didn't find anyone encourting such problem so that's why i am asking
Client.py
import socket # Import socket module
HOST = "localhost" # Host address / name
PORT = 2137 # Reserves port for the service
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
fileToSend = open('test.txt', 'rb')
print "File ready to be sent"
l = fileToSend.read(1024)
while l:
print "Sending the file"
client.send(l)
l = fileToSend.read(1024)
fileToSend.close() print "done"
client.close()
Server.py
import socket
from threading import Thread
from SocketServer import ThreadingMixIn
import sys
TCPHOST = "localhost"
TCPPORT = 2137
BUFFER_SIZE = 20
class ClientThread(Thread):
def __init__(self, HOST, PORT):
Thread.__init__(self)
self.HOST = HOST
self.PORT = PORT
print "New thread started for " + HOST + " on port " + str(PORT)
def run(self):
f = open('received.py', 'wb')
while True:
try:
data = conn.recv(1024)
except socket.error, e:
print "Error receiving data: %s" % e
sys.exit(1)
while data:
print "Receiving"
f.write(data)
data = conn.recv(1024)
f.close()
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((TCPHOST, TCPPORT))
print "Socket created"
except socket.error, err:
print "Failed to create socket" % err
threads = []
while True:
server.listen(4)
print "Waiting for connections"
(conn, (HOST, PORT)) = server.accept()
thread = ClientThread(HOST, PORT)
thread.start()
threads.append(thread)
for t in threads:
t.join()
I am not sure what you actually want to do, because I see that you import SocketServer however you are not using it all.
If you are trying to run a simple socket server then the class ClientThread and all the other stuff about threads in that file are not necessary.
The following code in server.py will do the job
import socket
import sys
TCPHOST = "localhost"
TCPPORT = 2137
BUFFER_SIZE = 20
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((TCPHOST, TCPPORT))
server.listen(4)
print "Socket created"
except socket.error, err:
print "Failed to create socket" % err
while True:
print "Waiting for connections"
(conn, (TCPHOST, TCPPORT)) = server.accept()
try:
while True:
data = conn.recv(1024)
f = open('received.py', 'wb')
if data:
print "Receiving " + data
f.write(data)
else:
f.close()
break;
except socket.error, e:
#pass
print "Error receiving data: %s" % e
#sys.exit(1)
finally:
conn.close()
However if you are trying to implement a threaded TCPServer using the ThreadingMixIn then you need to create a class that subclasses SocketServer and override its handle() function
Python documentation is quite helpful on this
https://docs.python.org/3.5/library/socketserver.html
(ThreadingMixin is at the bottom of the page)
I am trying to make a server that allows TCP, UDP and HTTP connections by making each process have its own thread. I already accomplished TCP and HTTP connections, and the UDP portion starts up correctly, but when I try to send a message via UDP, the system hangs. Does anyone know how to fix this problem?
The UDP Class Handler:
class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print("{} wrote: ".format(self.client_address[0]))
print(data)
socket.sendto(data.upper(), self.client_address)
The UDP Thread:
class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
pass
Location in code:
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "127.0.0.1", 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
http_thread = threading.Thread(target=httpd.serve_forever)
print("Website serving at port", PORT)
udpserver = ThreadedUDPServer((HOST,PORT+1), ThreadedUDPRequestHandler)
udp_thread = threading.Thread(target=udpserver.serve_forever)
print("UDP serving at port", PORT+1)
tcpserver = ThreadedTCPServer((HOST, PORT-1), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=tcpserver.serve_forever)
print("TCP serving at port", PORT-1)
udp_thread.start()
Solved:
I forgot to add
udp_thread.start()
I forgot to add
udp_thread.start()
at the bottom
I have recently been using Python's SimpleHTTPServer to host files on my network. I want a custom 404 Page, so I researched this and got some answers, but I want to still use this script I have. So, what do I have to add to get a 404 page to this script?
import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 80
server_address = ('192.168.1.100', port)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Being served on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
You implement your own request handler class and override the send_error method to change the error_message_format only when code is 404:
import os
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class MyHandler(SimpleHTTPRequestHandler):
def send_error(self, code, message=None):
if code == 404:
self.error_message_format = "Does not compute!"
SimpleHTTPRequestHandler.send_error(self, code, message)
if __name__ == '__main__':
httpd = HTTPServer(('', 8000), MyHandler)
print("Serving app on port 8000 ...")
httpd.serve_forever()
The default error_message_format is:
# Default error message template
DEFAULT_ERROR_MESSAGE = """\
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code %(code)d.
<p>Message: %(message)s.
<p>Error code explanation: %(code)s = %(explain)s.
</body>
"""
I'm trying to launch a simple server from a Python script:
server = Popen(['python' ,'-m', 'SimpleHTTPServer', '9090'], stderr=STDOUT, stdout=PIPE)
output = server.communicate()[0] # <- DEBUG
Reading the output, I see:
'/usr/bin/python: Import by filename is not supported.'
What's the problem? How to solve it?
I suggest change to code to this:
import SimpleHTTPServer
import SocketServer
PORT = 9090
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()