Search code examples
pythonlinuxbashstdingeoip

python sys.stdin.read() from tail -f


How come sys.stdin.read() doesn't read the piped input from tail -f?

#!/usr/bin/env python
import sys
from geoip import geolite2
def iplookup(srcip):
        for ip in srcip.split("\n"):
                try:
                        print(geolite2.lookup(ip))
                except:
                        pass
source = sys.stdin.read()
iplookup(source)

tail -f /var/log/bleh.log | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | python mygeoip.py


Solution

  • You can use sys.stdin as an iterator, rather than trying to read from it first.

    def iplookup(srcip):
        for ip in srcip:
            ip = ip.strip()
            try:
                print(geolite2.lookup(ip))
            except:
                pass
    
    iplookup(sys.stdin)