10.10. syslog


import syslog

syslog.syslog('Processing started')
if error:
    syslog.syslog(syslog.LOG_ERR, 'Processing started')

syslog.openlog(logopt=syslog.LOG_PID, facility=syslog.LOG_MAIL)
syslog.syslog('E-mail processing initiated...')
	

10.10.1. udp client

		
#!/usr/bin/python
# -*- encoding: iso-8859-1 -*-

"""
Python syslog client.

This code is placed in the public domain by the author.
Written by Christian Stigen Larsen.

This is especially neat for Windows users, who (I think) don't
get any syslog module in the default python installation.

See RFC3164 for more info -- http://tools.ietf.org/html/rfc3164

Note that if you intend to send messages to remote servers, their
syslogd must be started with -r to allow to receive UDP from
the network.
"""

import socket

# I'm a python novice, so I don't know of better ways to define enums

FACILITY = {
	'kern': 0, 'user': 1, 'mail': 2, 'daemon': 3,
	'auth': 4, 'syslog': 5, 'lpr': 6, 'news': 7,
	'uucp': 8, 'cron': 9, 'authpriv': 10, 'ftp': 11,
	'local0': 16, 'local1': 17, 'local2': 18, 'local3': 19,
	'local4': 20, 'local5': 21, 'local6': 22, 'local7': 23,
}

LEVEL = {
	'emerg': 0, 'alert':1, 'crit': 2, 'err': 3,
	'warning': 4, 'notice': 5, 'info': 6, 'debug': 7
}

def syslog(message, level=LEVEL['notice'], facility=FACILITY['daemon'],
	host='localhost', port=514):

	"""
	Send syslog UDP packet to given host and port.
	"""

	sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	data = '<%d>%s' % (level + facility*8, message)
	sock.sendto(data, (host, port))
	sock.close()
		
		

Example usage:

from syslog import syslog
message = 'There were zwei peanuts walking down der strasse...'
syslog(message, level=5, facility=3, host='localhost', port=514)
		

		
# -*- Mode: Python; tab-width: 4 -*-

# ======================================================================
# Copyright 1997 by Sam Rushing
# 
#                         All Rights Reserved
# 
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of Sam
# Rushing not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior
# permission.
# 
# SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
# NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# ======================================================================

"""socket interface to unix syslog.
On Unix, there are usually two ways of getting to syslog: via a
local unix-domain socket, or via the TCP service.

Usually "/dev/log" is the unix domain socket.  This may be different
for other systems.

>>> my_client = syslog_client ('/dev/log')

Otherwise, just use the UDP version, port 514.

>>> my_client = syslog_client (('my_log_host', 514))

On win32, you will have to use the UDP version.  Note that
you can use this to log to other hosts (and indeed, multiple
hosts).

This module is not a drop-in replacement for the python
<syslog> extension module - the interface is different.

Usage:

>>> c = syslog_client()
>>> c = syslog_client ('/strange/non_standard_log_location')
>>> c = syslog_client (('other_host.com', 514))
>>> c.log ('testing', facility='local0', priority='debug')

"""

# TODO: support named-pipe syslog.
# [see ftp://sunsite.unc.edu/pub/Linux/system/Daemons/syslog-fifo.tar.z]

# from <linux/sys/syslog.h>:
# ===========================================================================
# priorities/facilities are encoded into a single 32-bit quantity, where the
# bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
# (0-big number).  Both the priorities and the facilities map roughly
# one-to-one to strings in the syslogd(8) source code.  This mapping is
# included in this file.
#
# priorities (these are ordered)

LOG_EMERG		= 0		#  system is unusable 
LOG_ALERT		= 1		#  action must be taken immediately 
LOG_CRIT		= 2		#  critical conditions 
LOG_ERR			= 3		#  error conditions 
LOG_WARNING		= 4		#  warning conditions 
LOG_NOTICE		= 5		#  normal but significant condition 
LOG_INFO		= 6		#  informational 
LOG_DEBUG		= 7		#  debug-level messages 

#  facility codes 
LOG_KERN		= 0		#  kernel messages 
LOG_USER		= 1		#  random user-level messages 
LOG_MAIL		= 2		#  mail system 
LOG_DAEMON		= 3		#  system daemons 
LOG_AUTH		= 4		#  security/authorization messages 
LOG_SYSLOG		= 5		#  messages generated internally by syslogd 
LOG_LPR			= 6		#  line printer subsystem 
LOG_NEWS		= 7		#  network news subsystem 
LOG_UUCP		= 8		#  UUCP subsystem 
LOG_CRON		= 9		#  clock daemon 
LOG_AUTHPRIV	= 10	#  security/authorization messages (private) 

#  other codes through 15 reserved for system use 
LOG_LOCAL0		= 16		#  reserved for local use 
LOG_LOCAL1		= 17		#  reserved for local use 
LOG_LOCAL2		= 18		#  reserved for local use 
LOG_LOCAL3		= 19		#  reserved for local use 
LOG_LOCAL4		= 20		#  reserved for local use 
LOG_LOCAL5		= 21		#  reserved for local use 
LOG_LOCAL6		= 22		#  reserved for local use 
LOG_LOCAL7		= 23		#  reserved for local use 

priority_names = {
	"alert":	LOG_ALERT,
	"crit":		LOG_CRIT,
	"debug":	LOG_DEBUG,
	"emerg":	LOG_EMERG,
	"err":		LOG_ERR,
	"error":	LOG_ERR,		#  DEPRECATED 
	"info":		LOG_INFO,
	"notice":	LOG_NOTICE,
	"panic": 	LOG_EMERG,		#  DEPRECATED 
	"warn":		LOG_WARNING,		#  DEPRECATED 
	"warning":	LOG_WARNING,
	}

facility_names = {
	"auth":		LOG_AUTH,
	"authpriv":	LOG_AUTHPRIV,
	"cron": 	LOG_CRON,
	"daemon":	LOG_DAEMON,
	"kern":		LOG_KERN,
	"lpr":		LOG_LPR,
	"mail":		LOG_MAIL,
	"news":		LOG_NEWS,
	"security":	LOG_AUTH,		#  DEPRECATED 
	"syslog":	LOG_SYSLOG,
	"user":		LOG_USER,
	"uucp":		LOG_UUCP,
	"local0":	LOG_LOCAL0,
	"local1":	LOG_LOCAL1,
	"local2":	LOG_LOCAL2,
	"local3":	LOG_LOCAL3,
	"local4":	LOG_LOCAL4,
	"local5":	LOG_LOCAL5,
	"local6":	LOG_LOCAL6,
	"local7":	LOG_LOCAL7,
	}

import socket

class syslog_client:
	def __init__ (self, address='/dev/log'):
		self.address = address
		if type (address) == type(''):
			self.socket = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
			self.socket.connect (address)
			self.unix = 1
		else:
			self.socket = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
			self.unix = 0

	# curious: when talking to the unix-domain '/dev/log' socket, a
	#   zero-terminator seems to be required.  this string is placed
	#   into a class variable so that it can be overridden if
	#   necessary.

	log_format_string = '<%d>%s\000'

	def log (self, message, facility=LOG_USER, priority=LOG_INFO):
		message = self.log_format_string % (
			self.encode_priority (facility, priority),
			message
			)
		if self.unix:
			self.socket.send (message)
		else:
			self.socket.sendto (message, self.address)

	def encode_priority (self, facility, priority):
		if type(facility) == type(''):
			facility = facility_names[facility]
		if type(priority) == type(''):
			priority = priority_names[priority]			
		return (facility<<3) | priority

	def close (self):
		if self.unix:
			self.socket.close()		
		
		

10.10.2. udp server

		
import os,socket,sys,time,string
import MySQLdb
bufsize=1500
port=514
syslog_serverty={ 0:"emergency",
                   1:"alert",
                   2:"critical",
                   3:"error",
                   4:"warning",
                   5:"notice",
                   6:"info",
                   7:"debug"
                 }
syslog_facility={ 0:"kernel",
                   1:"user",
                   2:"mail",
                   3:"daemaon",
                   4:"auth",
                   5:"syslog",
                   6:"lpr",
                   7:"news",
                   8:"uucp",
                   9:"cron",
                   10:"authpriv",
                   11:"ftp",
                   12:"ntp",
                   13:"security",
                   14:"console",
                   15:"cron",
                   16:"local 0",
                   17:"local 1",
                   18:"local 2",
                   19:"local 3",
                   20:"local 4",
                   21:"local 5",
                   22:"local 6",
                   23:"local 7"
                 }
try:
  sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  sock.bind(("0.0.0.0",port))
except:
  print("error bind")
  sys.exit(1)
sql_em="insert into emergency values(%s,%s,%s,%s,%s,%s)"
sql_al="insert into alert     values(%s,%s,%s,%s,%s,%s)"
sql_cr="insert into critical  values(%s,%s,%s,%s,%s,%s)"
sql_er="insert into error     values(%s,%s,%s,%s,%s,%s)"
sql_wa="insert into warning   values(%s,%s,%s,%s,%s,%s)"
conn=MySQLdb.connect(host="127.0.0.1",db="syslog",port=18888,user="root",passwd="cinda")
curs=conn.cursor()
#f=file("syslog.txt","w")
print ("----------------syslog is start----------------\n")
try:
  while 1:
    try:
      data,addr=sock.recvfrom(bufsize)
      #print data,addr
      syslog=str(data)
      n=syslog.find('>')
      serverty=string.atoi(syslog[1:n])&0x0007
      facility=(string.atoi(syslog[1:n])&0x03f8)>>3
      syslog_msg=syslog[26:]
      dev_name=syslog_msg[:syslog_msg.find(' ')]
      dev_msg=syslog_msg[syslog_msg.find(' '):]
      param=(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()),dev_name,addr[0],syslog_facility[facility],syslog_serverty[serverty],dev_msg)

      if serverty==0:
        curs.execute(sql_em,param)
        print syslog_msg
      elif serverty==1:
        curs.execute(sql_al,param)
        print syslog_msg
      elif serverty==2:
        curs.execute(sql_cr,param)
        print syslog_msg
      elif serverty==3:
        curs.execute(sql_er,param)
        print syslog_msg
      elif serverty==4:
        curs.execute(sql_wa,param)
        print syslog_msg

      conn.commit()

      #print dev_msg,time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
      #print syslog_serverty[serverty],syslog_facility[facility],syslog[26:]
      #f.writelines(syslog_serverty[serverty]+" "+syslog_facility[facility]+" "+syslog[26:]+'\n')
    except socket.error:
      pass
except KeyboardInterrupt:
  curs.close()
  conn.close()
  print ("------------------syslogd stop-------------\n")
  print "good bye"
  sys.exit()
#f.close		
		
		




原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

优秀的个人博客,低调大师

微信关注我们

原文链接:https://yq.aliyun.com/articles/351556

转载内容版权归作者及来源网站所有!

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

相关文章

发表评论

资源下载

更多资源
优质分享Android(本站安卓app)

优质分享Android(本站安卓app)

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario,低调大师唯一一个Java游戏作品

Mario,低调大师唯一一个Java游戏作品

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Eclipse(集成开发环境)

Eclipse(集成开发环境)

Eclipse 是一个开放源代码的、基于Java的可扩展开发平台。就其本身而言,它只是一个框架和一组服务,用于通过插件组件构建开发环境。幸运的是,Eclipse 附带了一个标准的插件集,包括Java开发工具(Java Development Kit,JDK)。

Sublime Text 一个代码编辑器

Sublime Text 一个代码编辑器

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。