python-3.xprintingdebianfail2ban

How to cut specifics parts of a line with Python?


I'm trying to make a script that display recent Ban, Found or Unban infos that are in fail2ban logs (/var/log/fail2ban), but I want to hide this selection for all lines :

,325 fail2ban.actions [424]: NOTICE [sshd]

In order to have this :

2022-07-02 18:15:17 Unban 192.168.200.20

And not this :

2022-07-02 18:15:17,325 fail2ban.actions [424]: NOTICE [sshd] Unban 192.168.200.20

Here is my code :

with open('/var/log/fail2ban.log', 'r') as f:
     for line in f.readlines():
             if 'Ban' in line:
                   print(line)

             if 'Unban' in line:
                    print(line)

             if 'Found' in line:
                    print(line)

Solution

  • You can use replace function .

    with open('/var/log/fail2ban.log', 'r') as f:
        for line in f.readlines():
                line = line.replace('that string you dont want', '')
                if 'Ban' in line:
                      print(line)
                if 'Unban' in line:
                       print(line)
                if 'Found' in line:
                        print(line)