Python:获取连接服务器IP地址的详细信息

获取连接服务器IP地址的详细信息

代码:

# -*- coding: utf-8 -*-
import os
import time
import geoip2.database
from prettytable import PrettyTable


def get_ip():
    """
    活动OS当前活动连接IP地址列表(TOP 20)
    :return:
    """
    cmd = '''netstat -anlp|grep tcp |awk '{print $5}'|awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n20 '''
    result = []
    get_cmd = os.popen(cmd).readlines()
    for e in get_cmd:
        temp = e.lstrip()  # 删除左边的空格
        temp = temp.replace('\n', '')  # 删除换行符
        temp = temp.split(' ')
        result.append(temp)
    return result


def get_city(ip_addr):
    """
    获取IP地址的地理位置
    :param ip_addr:
    :return:
    """
    reader = geoip2.database.Reader('GeoLite2-City.mmdb')
    response = reader.city(ip_addr)
    _city = response.city.names.get('zh-CN', '')

    #_province = response.subdivisions.most_specific.names['zh-CN']
    #print(_province)

    _county = response.country.names['zh-CN']
    result = _county + _city
    return result

table = PrettyTable(["IP Address", "来自地区", "连接会话"])

ip_list = get_ip()
# print(ip_list)
for e in ip_list:
    ip_add = e[1]
    if ip_add == '127.0.0.1' or ip_add == '0.0.0.0':
        continue
    if ip_add.find('192.168') >= 0 or ip_add.find('10.0') >= 0 or ip_add.find('172.16.') >= 0:
        continue
    table.add_row([ip_add, get_city(ip_add), e[0]])

dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print('\033[1;31m', '检测时间:', dt, "\033[0m")

#table.reversesort = True
print(table)

测试

# python get_ip1.py 
 检测时间: 2019-01-18 18:46:01 
+-----------------+----------------+----------+
|    IP Address   |    来自地区    | 连接会话 |
+-----------------+----------------+----------+
|  125.41.133.197 |    中国郑州    |    18    |
| 221.176.120.221 |      中国      |    2     |
|  198.143.164.254 |   美国芝加哥   |    1     |
|  216.244.66.230 | 美国史帝文斯湖 |    1     |
|  117.159.26.226 |   中国周口市   |    1     |
+-----------------+----------------+----------+


点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注