简体   繁体   English

python sys.stdin.read()不需要的拆分

[英]python sys.stdin.read() unwanted split

i'm trying to make a script that i can pipe IP addresses to and have it return the geoip location. 我正在尝试制作一个脚本,可以将IP地址传送到该脚本,并使其返回geoip位置。 When I try this, it looks like its splitting each IP address by 1 character at a time and failing when trying to run iplookup() 当我尝试此操作时,它看起来像一次将每个IP地址分割为1个字符,而在尝试运行iplookup()时失败

#!/usr/bin/env python
import sys
from geoip import geolite2
def iplookup(srcip):
    for ip in srcip:
            print(ip)
            try:
                    print(geolite2.lookup(ip))
            except:
                    print("oops")
                    pass


source = sys.stdin.read()
iplookup(source)

Echo a sample of data (That in the future i would like to come from tail -f fast.log) command to extract only the IP addresses 回显数据样本(将来我希望来自tail -f fast.log)仅提取IP地址

[root@suricata py]# echo "05/20/2015-15:57:34.607470 [**] [1:2020702:2] ET DOS Bittorrent User-Agent inbound - possible DDOS [**] [Classification: Attempted Denial of Service] [Priority: 2] {TCP} 8.8.8.8:2039 -> 1.1.1.1:80" | 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

8
oops
.
oops
8
oops
.
oops
8
oops
.
oops
8
oops

etc... 等等...

sys.stdin.read() gives you a string, if you have comma separated IP addresses, Do something like this sys.stdin.read()为您提供一个字符串,如果您使用逗号分隔IP地址,请执行以下操作

source = sys.stdin.read()
for ip in source.split(","):
    print(geolite2.lookup(ip))

When you call iplookup("stackoverflow.com") , your python function is going to do exactly what you told it to do, which is to walk over the elements of the input array. 当您调用iplookup("stackoverflow.com") ,您的python函数将完全按照您的要求执行操作,即遍历输入数组的元素。 Your for loop tells python to walk over the list. 您的for循环告诉python浏览列表。

A string in python is a list of characters. python中的字符串是字符列表。

So either don't do that (kill the loop), or call your function via iplookup((source,)) , or iplookup([source]) . 因此,要么不要这样做(杀死循环),要么通过iplookup((source,))iplookup([source])调用函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM