通过命令行查找 IP 地理位置

通过命令行查找 IP 地理位置

我一直在尝试拼凑一个快速而粗糙的脚本来返回一堆 IP 地址的地理位置。

我正在使用 freegeoip.net,但找不到与 cmd 行等效的快速 wget,因此使用 powershell 脚本,从我的批处理文件中调用它(或者至少尝试一下,但我认为那是我失败的地方)。

命令行是:

for /F "tokens=* usebackq delims=" %a in ("E:\DATA\02.ips.txt") do (
set /a N+=1
 powershell -command "E:\DATA\Resources\geolocation.ps1 %a"
)

(需要跳过第一行,因为其中包含标题,而不是 IP)

geolocation.ps1 是:

wget freegeoip.net/csv/$args[0] -OutFile "E:\DATA\IPs\$args[0].txt"

我希望这会给我一个包含每个 IP 返回的 CSV 的文件夹,然后我可以将其整理成一个文件,副本为 E:\DATA\IPs*.txt alltheips.txt,然后将该文件加载到另一个应用程序中以供使用。

这个(显然)哈希是由我在谷歌上搜索到的和到处收集到的内容混合而成的,但是(显然)我实际上不知道我在这里做什么,因此,对于缺失的部分,任何帮助都将不胜感激!

简而言之,我想要的是获取我的 IP 地址列表(我有一个带有标题的文本文件,然后每行都是一个新的 IP,文件的长度为 x,每次运行时都会有所不同 - 有时它会是空的,所以如果我可以检查文件的长度并且它只包含标题以跳过该过程,那将很方便)。 对照 freegeoip.net 检查这些 IP,并将它们提供的数据整理到一个文件中,以便在程序中使用,该程序会将用户的位置与我通过 IP 保存的其他数据关联起来。

干杯!

答案1

将整个脚本放入脚本中。在这种情况下,无需将 PowerShell 包装在批处理文件中。实际上,这样做会损失很多,因为 PowerShell 是面向对象的。

# for the filename, this is a string
# quotes needed if there's a space, 
# use single quotes unless the string is an expression which needs evaluation
#
# Import-CSV builds an array of objects from the contents of the csv
# using the first row as a header
# in your case the objects will be strings which are IP addresses
# 
# For your own benefit, make sure the ip address column 
# (only one columnt per your post) has a simple title in the first row

$IPList = Import-CSV E:\DATA\02.ips.txt 

# the Foreach command is a for loop used with arrays or collections to loop through all the members

Foreach ($IPAddress in $IPList) {
    # In PowerShell, wget is an alias for Invoke-WebRequest
    # the $() wrapper around the $IPAddress.ipaddress is to force evaluation of that expression
    Invoke-WebRequest "freegeoip.net/csv/$($IPAddress.ipaddress)" -OutFile "E:\DATA\IPs\$($IPAddress.ipaddress).txt"
    }

答案2

这是我编写的一个批处理文件,它使用 ipinfo.io 的 API 执行 IP 查找。https://pastebin.com/Ucs2Kuqn 享受!

相关内容