Like Silk: Script: accesslimit

python関連のメモ

IPと全体のカウントに基づき実行回数を制限する

code

accesslimit.py←右クリックで保存できます.
#!/usr/bin/env python
#coding: utf-8

import fcntl
import time
try:
    import cPickle as pickle
except:
    import pickle

def accesscount( pklfilename, ip, timerangesec, ipcountlimit, totalcountlimit ):
	##### lock #####
	lockfilename = pklfilename + '.lock'
	fd = open(lockfilename, "w")
	fcntl.flock(fd,fcntl.LOCK_EX)
	##### lock #####
	
	try:
		fin = open(pklfilename, 'rb')
		accesslog = pickle.load( fin )
		fin.close()
	except:
		accesslog = []
	
	timestamp = int(time.time())
	timestamp0 = timestamp - timerangesec;
	
	ipcount = 0
	for al in accesslog[:]:
		if( al[0] < timestamp0 ):
			accesslog.remove( al )
		elif( al[1] == ip ):
			ipcount = ipcount + 1
			
	totalcount = len( accesslog )
	
	if( ipcount < ipcountlimit and totalcount < totalcountlimit ):
		accesslog.append( [timestamp, ip] )
		totalcount = totalcount + 1
		ipcount = ipcount + 1
		flg = True
	else:
		flg = False
	
	fout = open(pklfilename, 'wb')
	pickle.dump( accesslog, fout )
	fout.close()

	##### unlock #####
	fcntl.flock(fd,fcntl.LOCK_UN)
	fd.close()
	##### unlock #####

	return flg, ipcount, totalcount



if( __name__ == '__main__' ):
	logfilename = 'accesslog.pkl'
	timerangesec = 5
	ipcountlimit = 5
	totalcountlimit = 7

	ip1 = '192.168.0.1'
	ip2 = '192.168.0.2'

	for i in xrange(6):
		flg, ipc, totalc = accesscount(logfilename, ip1, timerangesec, ipcountlimit, totalcountlimit )
		print ip1, flg, ipc, totalc
		time.sleep(0.1)

	for i in xrange(5):
		flg, ipc, totalc = accesscount(logfilename, ip2, timerangesec, ipcountlimit, totalcountlimit )
		print ip2, flg, ipc, totalc
		time.sleep(0.1)

	print ''
	time.sleep(4.5)

	for i in xrange(6):
		flg, ipc, totalc = accesscount(logfilename, ip1, timerangesec, ipcountlimit, totalcountlimit )
		print ip1, flg, ipc, totalc
		time.sleep(0.1)

	for i in xrange(5):
		flg, ipc, totalc = accesscount(logfilename, ip2, timerangesec, ipcountlimit, totalcountlimit )
		print ip2, flg, ipc, totalc
		time.sleep(0.1)

参考URL


Like Silk