如何在日志文件中跟踪我的公共 IP 地址?

如何在日志文件中跟踪我的公共 IP 地址?

我想将我的公共 IP 地址保存到日志文件中,以便我可以使用它们在统计数据集合中排除我自己对我的网站的访问。此时我可以看到我的实际公网IP地址——Whatsmyip.org——但我相信每次我关闭调制解调器时,情况都会发生变化。

我没有静态公共 IP 地址,并且我认为我的 ISP 没有为我提供固定的 IP 范围。

我正在运行 Linux Mint 17.3,有什么办法可以让我有一个类似的日志文件吗?如果没有,我可以追踪我未来的 IP 吗?如何追踪?

答案1

这将为您提供您的公共 IP,删除/ip部分以查看更多信息。

$ curl ipinfo.io/ip

答案2

您可以尝试使用一些动态dns服务,例如noip.com,然后您可以通过dns名称访问资源,该名称会根据您的ip而变化。

一般来说,您的提供商可能会使用地址池进行 NAT。每个curl https://ipinfo.io/ip请求都会从该池中返回一个随机地址,具体取决于 NAT 的设置。

最好使用不同的方法来跟踪对网站的访问。铁饼干。

下面是一段用于放入 cron 并收集地址的 python 小代码:

#!/usr/bin/env python

from datetime import datetime
import os
import requests

LOG = '/tmp/ip.log'
URL = 'https://ipinfo.io/ip'

r = requests.get(URL)
if r.status_code == 200:
    ip = r.content.decode('ascii').rstrip('\n')
    last_ip = None
    if os.path.exists(LOG):
        f = open(LOG, 'r')
        last_ip = f.readlines()[-1].split()[-1]
        f.close()
    if ip != last_ip:
        f = open(LOG, 'a')
        f.write("{} {}\n".format(datetime.now(), ip))

答案3

将此行添加到您的 crontab 文件 ( crontab -e),以将日期和您的公共 IPv4 地址写入名为 的文件ip_public.txt,该文件保存在您的主目录中,每天中午 12:00。

0 0 * * * echo $(date +\%Y-\%m-\%d) $(curl https://ipinfo.io/ip 2>/dev/null) >> ~/ip_public.txt 2>&1

答案4

这里已经有了答案,但这是使用 DNS 获取公共 IP 地址的另一种方法。

dig +short myip.opendns.com @resolver1.opendns.com

然后您必须将其包装在脚本中以保存历史记录。

相关内容