Python Syslog server for network devices - python

Creating a python syslog server for my network devices I am using the below code that comes from here https://gist.githubusercontent.com/marcelom/4218010/raw/53b643bd056d03ffc21abcfe2e1b9f6a7de005f0/pysyslog.py
This will meet my needs but I cannot seem to get any python version of sysloghandler to run. I see this is old code about 5 years or so.
I am running ubuntu 16.04 system. Everything seems to hang on the try: for initiating the server.
#!/usr/bin/env python
## Tiny Syslog Server in Python.
##
## This is a tiny syslog server that is able to receive UDP based syslog
## entries on a specified port and save them to a file.
## That's it... it does nothing else...
## There are a few configuration parameters.
LOG_FILE = 'youlogfile.log'
HOST, PORT = "0.0.0.0", 514
#
# NO USER SERVICEABLE PARTS BELOW HERE...
#
import logging
import SocketServer
logging.basicConfig(level=logging.INFO, format='%(message)s', datefmt='', filename=LOG_FILE, filemode='a')
class SyslogUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = bytes.decode(self.request[0].strip())
socket = self.request[1]
print( "%s : " % self.client_address[0], str(data))
logging.info(str(data))
if __name__ == "__main__":
try:
server = SocketServer.UDPServer((HOST,PORT), SyslogUDPHandler)
server.serve_forever(poll_interval=0.5)
except (IOError, SystemExit):
raise
except KeyboardInterrupt:
print ("Crtl+C Pressed. Shutting down.")

Your code works for me. If I start the server like this:
sudo python server.py
And then send a message like this:
echo this is a test | nc -u localhost 514
I see output on stdout:
('127.0.0.1 : ', 'this is a test')
And the file youlogfile.log contains:
this is a test
I suspect your problems stem from trying to use a TCP tool to connect to a UDP server.

Related

Setting up handlers in pyst2 fastagi code

I am trying to create a fastagi server for executing some agi scripts.
I'm using pyst2 to setup fast agi server. the script running fast agi server is as follows:
#!/usr/bin/env python
"""
.. module:: fastagi
:synopsis: FastAGI service for Asterisk
Requires modified pyst2 to support reading stdin/out/err
Copyright 2011 VOICE1, LLC
By: Ben Davis <ben#voice1-dot-me>
Specification
-------------
"""
import sys
import SocketServer
import asterisk.agi
# import pkg_resources
# PYST_VERSION = pkg_resources.get_distribution("pyst2").version
__verison__ = 0.1
#TODO: Read options from config file.
HOST, PORT = "127.0.0.1", 4573
class FastAGI(SocketServer.StreamRequestHandler):
# Close connections not finished in 5seconds.
timeout = 5
def handle(self):
try:
agi=asterisk.agi.AGI(stdin=self.rfile, stdout=self.wfile,
stderr=sys.stderr)
agi.verbose("pyst2: FastAGI on: {}:{}".format(HOST, PORT))
except TypeError as e:
sys.stderr.write('Unable to connect to agi://{}
{}\n'.format(self.client_address[0], str(e)))
except SocketServer.socket.timeout as e:
sys.stderr.write('Timeout receiving data from
{}\n'.format(self.client_address))
except SocketServer.socket.error as e:
sys.stderr.write('Could not open the socket. Is someting else
listening on this port?\n')
except Exception as e:
sys.stderr.write('An unknown error: {}\n'.format(str(e)))
if __name__ == "__main__":
# server = SocketServer.TCPServer((HOST, PORT), FastAGI)
server = SocketServer.ForkingTCPServer((HOST, PORT), FastAGI)
# Keep server running until CTRL-C is pressed.
server.serve_forever()
Its ok when I use the following context.
exten => 123,1,agi(agi://FASTAGI_IP_address)
but I want to have more than 1 scripts like
exten => 123,1,agi(agi://FASTAGI_IP_address/handler_name)
I don't know how to use some handler names in fast agi server codes.
I'm new to python so I will be very thankful if I can have some clear guidance on how to add extra handlers in fastagi code.
Found the solution. on the asterisk server I was contacting the Fastagi server using below dialplan:
extension=> s,1,AGI(agi://server-address/handler)
the "handler" showing in above code is returning to fastagi server as "agi.env['agi_network_script']".
a simple example on how to use handler is like the below code:
class FastAGI(SocketServer.StreamRequestHandler):
def handle(self):
try:
agi=asterisk.agi.AGI(stdin=self.rfile, stdout=self.wfile, stderr=sys.stderr)
handler = agi.env['agi_network_script']
### Managing Handler Section ###
if handler == 'handler1':
// Do whatever you wanna do with handler2
elif handler == 'handler2':
// Do whatever you wanna do with handler2
except TypeError as e:
sys.stderr.write('Unable to connect to agi://{} {}\n'.format(self.client_address[0], str(e)))
except SocketServer.socket.timeout as e:
sys.stderr.write('Timeout receiving data from {}\n'.format(self.client_address))
except SocketServer.socket.error as e:
sys.stderr.write('Could not open the socket. Is someting else listening on this port?\n')
except Exception as e:
sys.stderr.write('An unknown error: {}\n'.format(str(e)))
if __name__ == "__main__":
server = SocketServer.ForkingTCPServer((HOST, PORT), FastAGI)
server.serve_forever()

Reconnecting a Bluetooth device using socket library (RFCOMM mode) in python 3?

I am trying to connect to a Bluetooth GPS unit from a Raspberry Pi3 using the socket library in python 3. I am able to connect and get data flowing the first time but if I disconnect and then try reconnecting I get:
[Errno 16] Device or resource busy
I have tried placing the connection in a sub process killing it and recreating it (end goal) and I get the same error. If I close and restart the test program it connects no problem.
Here is a test script based on a demo I found, that opens the connection closes it then tries to reconnect for ever. When I try it I get tick tick tick... until I hit ^c to kill it
import io
import socket
from time import sleep
from bluetooth import *
import sys
class SocketIO(io.RawIOBase):
def __init__(self, sock):
self.sock = sock
def read(self, sz=-1):
if (sz == -1): sz=0x7FFFFFFF
return self.sock.recv(sz)
def seekable(self):
return False
# file: l2capclient.py
# desc: Demo L2CAP client for bluetooth module.
# $Id: l2capclient.py 524 2007-08-15 04:04:52Z albert $
if sys.version < '3':
input = raw_input
if len(sys.argv) < 2:
print("usage: l2capclient.py <addr>")
sys.exit(2)
bt_addr=sys.argv[1]
port = 1
print("trying to connect to %s on PSM 0x%X" % (bt_addr, port))
# Create the client socket
sock=BluetoothSocket( RFCOMM )
sock.connect((bt_addr, port))
fd = SocketIO(sock)
bno = 0
for line in fd:
print(line)
bno +=1
if bno >10:
break
sock.shutdown(socket.SHUT_RDWR)
sock.close()
print("closed")
sock=BluetoothSocket( RFCOMM )
not_connected = True
while not_connected:
try:
sock.connect((bt_addr, port))
not_connected = False
except:
sleep(1)
print("tick")
pass
fd = SocketIO(sock)
try:
for line in fd:
print(line)
except IOError:
pass
sock.close()
The SocketIO class is just for convenience of getting data line by line I have tried it with sock.recv(1024) and got the same results.
I have a similar issue. I send data to an HC-05 bluetooth module from my PC using python sockets and a bluetooth RFCOMM socket. Here are a few things which have seemed to improve the debugging situation working with bluetooth...
If you havent already, make your socket a nonblocking socket, it sends out a flag when something goes wrong instead of crashing the program
Make sure you close the connection properly (it seems that you are doing that though)
Make sure that the GPS has no factory settings that prevent you from connecting instantly again. It could maybe have to do with a factory setting/timeout thing not agreeing with the way you request to connect again, and that error could be due to your code and quite possibly in a factory setting if there are any.

Execute python script on remote server from another script

import os
import sys
import commands
os.system('cat disk_space.py | ssh niraj#abc python - "sys.argv[1]"')
O/P:
python: No match.
Any idea ?
Directly run python script in your server, listen some one port which is not be used. when the port receive a signal, run the script which you want execute.
How to create socket service:
def tcplink(sock, addr):
print('Accept new connection from %s:%s...' % addr)
sock.send(b'Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if not data or data.decode('utf-8') == 'exit':
break
# execute what you want
sock.close()
print('Connection from %s:%s closed.' % addr)
Keep service alive in your server.

http webserver and I/O read write on Raspberry

I use http webserver python script:
class PiFaceWebHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
[....]
if __name__ == "__main__":
# get the port
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = DEFAULT_PORT
# set up PiFace Digital
PiFaceWebHandler.pifacedigital = pifacedigitalio.PiFaceDigital()
print("Starting simple PiFace web control at:\n\n"
"\thttp://{addr}:{port}\n\n"
"Change the output_port with:\n\n"
"\thttp://{addr}:{port}?output_port=0xAA\n"
.format(addr=get_my_ip(), port=port))
# run the server
server_address = ('', port)
try:
httpd = http.server.HTTPServer(server_address, PiFaceWebHandler)
httpd.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
httpd.socket.close()
It's working fine, but i want the script (or another one, ) check some I/O continuously, in a while loop, ie.
And sometimes this I/O could change state with http request.
Currently, I/O changes state on http request, but i don't find the tips to change them on external trigger (another input ie).
How can i do? Where can i code the loop test?
do I make myself clear?
Thanks,

Connect to Socket on localhost

I have trouble connecting to my own socket on localhost.
s.connect(('127.0.0.1', 4458)) (or "localhost") will just take forever,
and eventually timeout with TimeoutError: [Errno 110] Connection timed out
It should open port 4458, another script will then send some chars to it. Both scripts are supposed to run on the same Raspberry Pi, while 'server' one will execute with sudo (to access the GPIOs) and one without, being a chat bot.
I have no trouble running the server on the Pi (with python 3.4.1) and the client on my Laptop (mac, python 3.4.2).
Also it does work in reverse direction, server script on the laptop and client on the Raspberry.
As final test, it works with both, the server and the client on the said macbook.
Just server + client on the Pi does not work.
The program freezes
My shortened code if it helps:
# $ sudo python3 server.py
__author__ = 'luckydonald'
import socket # server
import time # wait for retry
import threading
class Server(threading.Thread):
port = 4458;
QUIT = False
def run(self):
s = socket.socket()
failed = True
print ("Starting Server on Port %d" % (self.port))
while failed:
try:
s.bind(("", self.port))
except Exception as err:
print(err)
print("Port assignment Failed. Retring in 1 second.")
time.sleep(1)
else:
failed = False
print("Success.")
while not self.QUIT:
print("Listening!")
conn, addr = s.accept() # freezes here
print("Got something: %s , %s" %(str(conn), str(addr)))
while not self.QUIT:
result = conn.recv(1)
print("Got result: " + str(result))
server = Server();
server.daemon = True
server.run();
# server.start();
And for the client:
# python3 cilent.py
s = socket.socket()
print("connecting...")
s.connect(("localhost",4458)) # also tried "172.0.0.1" # freezes here
print("connected!")
s.sendall("+".encode("utf-8"))
s.sendall("-".encode("utf-8"))
s.close()
It will result in this:
What I didn't expected was that localhost/127.0.0.1 did not work.
100% package loss
I had a malformatted entry in my hosts file.
You should check for below items
there is an installed internet information services
iis is running
firewall is grants required ports for running the python.exe

Categories