Adding IPv6 to fail2ban sensor (#19457)

* Fixing fail2ban regex for ipv6

* Adding IPv6 tests for fail2ban

* Formating code for hound

* Formating again

* Formating again 2
This commit is contained in:
Antoine GRÉA 2019-01-11 21:54:47 +01:00 committed by Paulus Schoutsen
parent 8ef2f1f67b
commit 14dd8791ec
2 changed files with 22 additions and 1 deletions

View File

@ -64,7 +64,7 @@ class BanSensor(Entity):
self.last_ban = None
self.log_parser = log_parser
self.log_parser.ip_regex[self.jail] = re.compile(
r"\[{}\].(Ban|Unban) ([\w+\.]{{3,}})".format(re.escape(self.jail))
r"\[{}\]\s*(Ban|Unban) (.*)".format(re.escape(self.jail))
)
_LOGGER.debug("Setting up jail %s", self.jail)

View File

@ -19,6 +19,10 @@ def fake_log(log_key):
'2017-01-01 12:23:35 fail2ban.actions [111]: '
'NOTICE [jail_one] Ban 111.111.111.111'
),
'ipv6_ban': (
'2017-01-01 12:23:35 fail2ban.actions [111]: '
'NOTICE [jail_one] Ban 2607:f0d0:1002:51::4'
),
'multi_ban': (
'2017-01-01 12:23:35 fail2ban.actions [111]: '
'NOTICE [jail_one] Ban 111.111.111.111\n'
@ -112,6 +116,23 @@ class TestBanSensor(unittest.TestCase):
assert \
sensor.state_attributes[STATE_ALL_BANS] == ['111.111.111.111']
def test_ipv6_ban(self):
"""Test that log is parsed correctly for IPV6 bans."""
log_parser = BanLogParser(timedelta(seconds=-1), '/tmp')
sensor = BanSensor('fail2ban', 'jail_one', log_parser)
assert sensor.name == 'fail2ban jail_one'
mock_fh = MockOpen(read_data=fake_log('ipv6_ban'))
with patch('homeassistant.components.sensor.fail2ban.open', mock_fh,
create=True):
sensor.update()
assert sensor.state == '2607:f0d0:1002:51::4'
assert \
sensor.state_attributes[STATE_CURRENT_BANS] == \
['2607:f0d0:1002:51::4']
assert \
sensor.state_attributes[STATE_ALL_BANS] == ['2607:f0d0:1002:51::4']
def test_multiple_ban(self):
"""Test that log is parsed correctly for multiple ban."""
log_parser = BanLogParser('/tmp')