Why python-iptables has problem when working with syslog module

167 views Asked by At

I met a strange bug. I have worked on it for 2 days, but failed to solve it. So I want to post it here to see if someone can help on this. I found python-iptables(iptc) cannot work with syslog module. Please see the following code. test1() will only send the first 2 log messages. test2 and test3 works properly. I tested this on both ubuntu16.04 and 20.04, python3.6 and python3.8.

import syslog
import iptc # pip install python-iptables
import os
import socket

def log(msg):
    syslog.openlog(ident="xxxxxx")
    syslog.syslog(syslog.LOG_INFO, msg)
    syslog.closelog()

def log2(msg):
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM|socket.SOCK_CLOEXEC)
    sock.connect("/dev/log")
    sock.send(("  xxxxxx: "+msg).encode("utf-8"))
    sock.close()

def add_rule_cmdline():
    os.system("iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT")

def add_rule_iptc():
    table = iptc.Table(iptc.Table.FILTER)
    chain = iptc.Chain(table, "INPUT")
    rule1 = {'target': 'ACCEPT','conntrack': {'ctstate': 'RELATED,ESTABLISHED'}}
    chain.append_rule(iptc.easy.encode_iptc_rule(rule1))
    table.close()

#no test2 received
def test1():  
    log("test0")
    os.system("iptables -F")
    log("test1")
    add_rule_iptc()
    log("test2")

#working
def test2():  
    log("test0")
    os.system("iptables -F")
    log("test1")
    add_rule_cmdline()
    log("test2")

#working
def test3():  
    log2("test0")
    os.system("iptables -F")
    log2("test1")
    add_rule_iptc()
    log2("test2")
0

There are 0 answers