From ee94daa12137a98a45a7d1c3b301fad372610a4a Mon Sep 17 00:00:00 2001 From: sebres Date: Wed, 14 May 2014 16:01:35 +0200 Subject: [PATCH] introduced string to seconds (str2seconds) for configuration entries with time; todo: expands it for all time config entries; --- fail2ban/server/mytime.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/fail2ban/server/mytime.py b/fail2ban/server/mytime.py index 166f4796..34a0eb42 100644 --- a/fail2ban/server/mytime.py +++ b/fail2ban/server/mytime.py @@ -22,6 +22,7 @@ __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" import datetime +import re import time @@ -96,3 +97,31 @@ class MyTime: return time.localtime(x) else: return time.localtime(MyTime.myTime) + + ## + # Wraps string expression like "1h 2m 3s" into number contains seconds (3723). + # The string expression will be evaluated as mathematical expression, spaces between each groups + # will be wrapped to "+" operand (only if any operand does not specified between). + # Because of case insensitivity and overwriting with minutes ("m" or "mm"), the short replacement for month + # are "mo" or "mon" (like %b by date formating). + # Ex: 1hour+30min = 5400 + # 0d 1h 30m = 5400 + # 1year-6mo = 15778800 + # 6 months = 15778800 + # warn: month is not 30 days, it is a year in seconds / 12, the leap years will be respected also: + # >>>> float(Test.str2seconds("1month")) / 60 / 60 / 24 + # 30.4375 + # >>>> float(Test.str2seconds("1year")) / 60 / 60 / 24 + # 365.25 + # + # @returns number (calculated seconds from expression "val") + + #@staticmethod + def str2seconds(val): + for rexp, rpl in ( + (r"days?|da|dd?", 24*60*60), (r"week?|wee?|ww?", 7*24*60*60), (r"months?|mon?", (365*3+366)*24*60*60/4/12), (r"years?|yea?|yy?", (365*3+366)*24*60*60/4), + (r"seconds?|sec?|ss?", 1), (r"minutes?|min?|mm?", 60), (r"hours?|ho|hh?", 60*60), + ): + val = re.sub(r"(?i)(?<=[\d\s])(%s)\b" % rexp, "*"+str(rpl), val) + val = re.sub(r"(\d)\s+(\d)", r"\1+\2", val); + return eval(val)