顯示具有 maxmind 標籤的文章。 顯示所有文章
顯示具有 maxmind 標籤的文章。 顯示所有文章

2021年4月22日 星期四

[PHP] 下載 Maxmind GeoIP Legacy Databases 和 ngx_http_geoip_module 相關處理 @ macOS 11.2, PHP 7.3.24

由於 Maxmind 在推 GeoIP2 ,不開放 .dat 的 GeoIP DB 了,以前下載位置:

  • http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
  • http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
現在官方都說要改用 GeoLite2 DB ,其格式:
  • GeoIP2 Binary (.mmdb)
  • GeoIP2 CSV 
目前先偷懶不處理 nginx ,因為 nginx 採用 GeoIP Legacy Databases。

有找到一個網站 https://www.miyuru.lk/geoiplegacy,從中下載:
連續動作:

% php -v
WARNING: PHP is not recommended
PHP is included in macOS for compatibility with legacy software.
Future versions of macOS will not include PHP.
PHP 7.3.24-(to be removed in future macOS) (cli) (built: Dec 21 2020 21:33:25) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.24, Copyright (c) 1998-2018 Zend Technologies

% php composer.phar require geoip/geoip:~1.16

% wget https://dl.miyuru.lk/geoip/maxmind/city/maxmind4.dat.gz
% gunzip -d maxmind4.dat.gz

% cat test-ip-via-geoip.php
<?php
require 'vendor/autoload.php';
$gi = geoip_open("maxmind4.dat",GEOIP_STANDARD);
$country = geoip_country_code_by_addr($gi, $argv[1]);
echo "lookup [".$argv[1]."], result: [$country]\n";

% php test-ip-via-geoip.php 8.8.8.8
lookup [8.8.8.8], result: [US]

% nslookup tw.yahoo.com
Server: 8.8.8.8
Address: 8.8.8.8#53

Non-authoritative answer:
tw.yahoo.com canonical name = atsv2-fp-shed.wg1.b.yahoo.com.
Name: atsv2-fp-shed.wg1.b.yahoo.com
Address: 180.222.102.201
Name: atsv2-fp-shed.wg1.b.yahoo.com
Address: 180.222.102.202

% php test-ip-via-geoip.php 180.222.102.202
lookup [180.222.102.202], result: [IN]

% curl ipinfo.io/180.222.102.202
{
  "ip": "180.222.102.202",
  "hostname": "media-router-fp74.prod.media.vip.tp2.yahoo.com",
  "city": "Taoyuan City",
  "region": "Taiwan",
  "country": "TW",
  "loc": "24.9937,121.2970",
  "org": "AS24506 YAHOO! TAIWAN",
  "timezone": "Asia/Taipei",
  "readme": "https://ipinfo.io/missingauth"
}

% nslookup facebook.com
Server: 8.8.8.8
Address: 8.8.8.8#53

Non-authoritative answer:
Name: facebook.com
Address: 31.13.87.36

% curl ipinfo.io/31.13.87.36
{
  "ip": "31.13.87.36",
  "hostname": "edge-star-mini-shv-01-tpe1.facebook.com",
  "city": "Hong Kong",
  "region": "Central and Western",
  "country": "HK",
  "loc": "22.2783,114.1747",
  "org": "AS32934 Facebook, Inc.",
  "timezone": "Asia/Hong_Kong",
  "readme": "https://ipinfo.io/missingauth"
}

% nslookup www.gov.tw
Server: 8.8.8.8
Address: 8.8.8.8#53

Non-authoritative answer:
Name: www.gov.tw
Address: 223.200.155.55

% php test-ip-via-geoip.php 223.200.155.55
lookup [223.200.155.55], result: [TW]

% curl ipinfo.io/223.200.155.55
{
  "ip": "223.200.155.55",
  "hostname": "223-200-155-55.hinet-ip.hinet.net",
  "city": "Hualien City",
  "region": "Taiwan",
  "country": "TW",
  "loc": "23.9769,121.6044",
  "org": "AS4782 Data Communication Business Group",
  "timezone": "Asia/Taipei",
  "readme": "https://ipinfo.io/missingauth"
}

2021年4月9日 星期五

[PHP] 透過 Maxmind GeoIP DB 統計用戶資訊 @ macOS 11.2, PHP 7.3.24

真是超級久沒用 maxmind.com 的 GeoIP DB 了,一時之間還以為沒有免費使用的方式,追了一下是要註冊帳號才能下載,而 maxmind 也有提供自動化每天更新 GeoIP DB 的機制。

在此對一份類似 Access Logs 做分析,將其轉成 CSV 格式來分析,其中 CSV 裡頭有 id 跟 remote_ip 兩個欄位,將 remote_ip 分析完後直接歸類屬於哪個 country_code,程式碼很簡單:

% php -v

WARNING: PHP is not recommended
PHP is included in macOS for compatibility with legacy software.
Future versions of macOS will not include PHP.
PHP 7.3.24-(to be removed in future macOS) (cli) (built: Dec 21 2020 21:33:25) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.24, Copyright (c) 1998-2018 Zend Technologies

% cat composer.json
{
  "require": {
    "geoip2/geoip2": "~2.0"
  }
}

% php composer.phar install
No lock file found. Updating dependencies instead of installing from lock file. Use composer update over composer install if you do not have a lock file.
Loading composer repositories with package information
Updating dependencies
Lock file operations: 4 installs, 0 updates, 0 removals
- Locking composer/ca-bundle (1.2.9)
- Locking geoip2/geoip2 (v2.11.0)
- Locking maxmind-db/reader (v1.10.0)
- Locking maxmind/web-service-common (v0.8.1)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
- Installing composer/ca-bundle (1.2.9): Extracting archive
- Installing maxmind/web-service-common (v0.8.1): Extracting archive
- Installing maxmind-db/reader (v1.10.0): Extracting archive
- Installing geoip2/geoip2 (v2.11.0): Extracting archive
2 package suggestions were added by new dependencies, use `composer suggest` to see details.

Generating autoload files
1 package you are using is looking for funding.
Use the `composer fund` command to find out more!

% cat job.php
<?php

require 'vendor/autoload.php';

// https://github.com/maxmind/GeoIP2-php
use GeoIp2\Database\Reader;
$reader = new Reader('GeoLite2-City.mmdb');

// https://www.php.net/manual/en/function.fgetcsv.php
$row = 1;
$header_row = NULL;
$header = array();
$country_group = array(); 
$lookup = array();

$tracking_time_cost_per_run = microtime(true);
echo "[".date("Y-m-d H:i:s")."]\tinit\n";
if (($handle = fopen("access_log.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10240, ",")) !== FALSE) {
if (is_null($header_row)) {
$header_row = $data;
foreach($header_row as $index => $name) {
$header[$name] = $index;
}
continue;
}
$remote_ip = $data[ $header['remote_ip'] ];
$data_id = $data[ $header['id'] ];

try {
$record = $reader->city($remote_ip);
} catch (Exception $e) {
continue;
}
if (!is_null($record) && property_exists($record, 'country') && !is_null($record->country) && isset($record->country->isoCode)) {
if (!isset($country_group[$record->country->isoCode]))
$country_group[$record->country->isoCode] = array();
$hash_key = $remote_ip.'-'.$record->country->isoCode;
if (!isset($lookup[$hash_key])) {
$lookup[$hash_key] = 1;
array_push($country_group[$record->country->isoCode], $data_id);
}
}
++$row;
if ($row % 100000 == 0) {
echo "[".date("Y-m-d H:i:s")."]\t".number_format($row).", time cost: ".(microtime(true) - $tracking_time_cost_per_run)."\n";
$tracking_time_cost_per_run = microtime(true);
file_put_contents('/tmp/lookup-result.json', json_encode($country_group));
}
}
fclose($handle);

echo "[".date("Y-m-d H:i:s")."]\t".number_format($row)."\n";
echo "Total #: $row\n";
print_r($header);
file_put_contents('lookup-result.json', json_encode($country_group));
}

產出:
% time php job.php
[2021-04-09 21:03:51] init
[2021-04-09 21:05:18] 100,000, time cost: 86.867056131363
[2021-04-09 21:06:41] 200,000, time cost: 83.395349025726 
...

% jq '' /tmp/lookup-result.json | head -n10

{
  "TW": [
    "1",
    "68",
    "101",
    "121",
    "147",
    "193",
    "236",
    "259", 
... 

就把一堆 record id 擺在某個 country_code 下面,每 85秒處理完 10萬筆資料。

2016年9月7日 星期三

[Linux] Nginx 啟用 nginx-module-geoip @ Ubuntu 14.04

Nginx 從 1.9.1 起,支援 Dynamic Modules 囉,此例是想要使用 MaxMind 來進行 IP 反查,接著想說有沒有方便的整合方式,像是寫 PHP 就用 MaxMind PHP library 等。

接著,就先查一下自己的 nginx 情況吧!

$ nginx -V
nginx version: nginx/1.10.1
... 找關鍵字 ...
--with-http_geoip_module=dynamic
...


很 OK ,接著再裝一下 ngx_http_geoip_module.so 吧!

$ apt-cache search nginx-module-geoip
nginx-module-geoip - geoip module
$ sudo apt-get install nginx-module-geoip
...
The GeoIP dynamic module for nginx has been installed.
To enable this module, add the following to /etc/nginx/nginx.conf
and reload nginx:

    load_module modules/ngx_http_geoip_module.so;

Please refer to the module documentation for further details:
http://nginx.org/en/docs/http/ngx_http_geoip_module.html
...


下載 MaxMind 資料:

$ curl http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz | gunzip - > /data/GeoIP.dat
$ curl http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz | gunzip - > /data/GeoLiteCity.dat


設置 Nginx,把 load_module 擺在最前頭
$ sudo vim /etc/nginx/nginx.conf
load_module "modules/ngx_http_geoip_module.so";
...

http {
    #geoip_country /data/GeoIP.dat;
    geoip_city    /data/GeoLiteCity.dat;
    ...

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" '
                      'GeoCountry[ "$geoip_country_name" "$geoip_country_code" "$geoip_country_code3" ] '
                      'GeoCity[ "$geoip_city_country_code" "$geoip_city_country_code3" "$geoip_city_country_name" ] '
                      'GeoLocation[ "$geoip_latitude" "$geoip_longitude" "$geoip_region" "$geoip_region_name" "$geoip_city" "$geoip_postal_code" ] '
    ;

    access_log  /var/log/nginx/access.log  main;
...

$ sudo service nginx reload


如此一來,就可以翻 /var/log/nginx/access.log 看看豐富的 GeoInfo 啦

2014年9月12日 星期五

[Python] 使用 Apache Web Server Access.log 把玩 CartoDB 視覺化地圖 @ Ubuntu 12.04



只要資料有 Geolocation,就能夠把玩 CartoDB 了 :P 若可以的話,再加上時間就更完美了。因此,最容易拿到的測資是 Apache web server log,把 access.log 挑點東西出來即可,至於 Geolocation 就用 ip 反查吧!

從 access.log 取出 ip list:

$ grep -v "^localhost\|::1" /var/log/apache2/access.log | awk '{print $1}' | uniq

首先,先到 Maxmind 下載最新的 GeoLite2-City 資訊:

$ wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz
$ gunzip GeoLite2-City.mmdb.gz


安裝 geoip-bin 工具:

$ sudo apt-get install geoip-bin
$ geoiplookup 8.8.8.8
GeoIP Country Edition: US, United States

$ geoiplookup -f GeoLite2-City.mmdb 8.8.8.8
Error Traversing Database for ipnum = 134744072 - Perhaps database is corrupt?
Segmentation fault (core dumped)


囧...只好裝一下新版 maxmind python sdk 寫一段小 code:

$ sudo pip install geoip2

$ vim t.py
mport sys
import geoip2.database
reader = geoip2.database.Reader('GeoLite2-City.mmdb')
try:
        response = reader.city(sys.argv[1])
        print str(response.location.latitude)+","+str(response.location.longitude)
except Exception, e:
        pass
$ python t.py 8.8.8.8
37.386,-122.0838


接著,就乾脆寫 python 來處理 access.log 吧 XDD 用 command line 好像太冗長了。

$ sudo cp /var/log/apache2/access.log /tmp/access.log
$ sudo chmod 644 /tmp/access.log
$ vim log.py
import geoip2.database
reader = geoip2.database.Reader('GeoLite2-City.mmdb')
try:
        log = open('/tmp/access.log','rb').read()
        for rec in log.split('\n'):
                fields = rec.split(' ')
                try:
                        if fields[0] == 'localhost' or fields[0] == '::1' :
                                continue
                        response = reader.city(fields[0])
                        print fields[3][1:]+","+str(response.location.latitude)+","+str(response.location.longitude)
                except Exception, e:
                        pass
except Exception, e:
        pass

$ python log.py > log.csv
$ cat log.csv
...
07/Sep/2014:22:12:43,35.685,139.7514
07/Sep/2014:22:13:53,39.4899,-74.4773
...


對於時間格式不用擔心,直接丟進 cartodb.com 請他幫你處理!




匯入後,預設都是 string,可以把 field1 設成 date type,field2 跟 field3 都設成 number type,弄完順便 rename 一下,接著再點選 geo 欄位,可以採用 field2 跟 field3 來生成,如此就完成 CartoDB  table 製作。








最後再去視覺化那邊,挑一下以 date 為基準的時間變化,就可以有不錯的視覺圖表。

2014年6月25日 星期三

[Linux] Apache/GeoIP/mod_geoip: 依據 Client IP Country 回傳指定 Server Location @ Ubuntu 14.04、Apache 2.4.7

$ apt-cache show libapache2-mod-geoip
Package: libapache2-mod-geoip
Priority: optional
Section: universe/web
Installed-Size: 86
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Prach Pongpanich <prachpub@gmail.com>
Architecture: amd64
Version: 1.2.8-2
Depends: apache2-api-20120211, libc6 (>= 2.3.4), libgeoip1
Filename: pool/universe/liba/libapache2-mod-geoip/libapache2-mod-geoip_1.2.8-2_amd64.deb
Size: 18748
MD5sum: fc16528f6d8acabaf8d40c70fe47b1b2
SHA1: 457df303c09556297a8b1f6887fe7a901d8bd063
SHA256: 26eabfe728014a506186f2856a3149f00e7bfcb6db9226dbfe13976ab3b4d584
Description-en: GeoIP support for apache2
 This is an apache2 module for finding the country that a web request
 originated from. It uses the GeoIP library and database to perform
 the lookup. The module allows manipulation of client requests from within
 Apache based on the country of origin.
 .
 This module only works on Apache 2 servers.
Description-md5: e4085008663af571952df21045e8534a
Homepage: http://www.maxmind.com/app/mod_geoip
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Origin: Ubuntu

$ sudo apt-get install libapache2-mod-geoip

$ ls -la /usr/share/GeoIP/
total 3852
-rw-r--r--   1 root root  827301 Apr  7 14:20 GeoIP.dat
-rw-r--r--   1 root root 3105495 Apr  7 14:21 GeoIPv6.dat


基本上安裝完就等同啟動 mod_geoip ,可以在 /etc/apache2/mods-enabled 看到 geoip.conf, geoip.load 蹤影。

編輯 Apache configure file:

<IfModule mod_geoip.c>
        GeoIPEnable On
        <IfModule mod_rewrite.c>
                RewriteEngine On
                RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CN$
                RewriteRule ^(.*)$ http://example.com.cn$1 [L]
        </IfModule>
</IfModule>


如此一來,當 Client IP 判斷是 CN 時,透過 Web Server 導向 CN 區的機器。

使用這招的目的是...大陸架設服務時,需要"備案",在備案還沒通過時,使用 domainname 連線過去的機器會被 ban 掉,這時候可以先稍微用已備案的或是 IP 來頂替了。

當備案成功後,就可以大方地使用 GeoDNS 的解法,讓使用者不必先連到指定機器再轉址。

最後,如果要留一些 debug 模式,可以多加上 hostname 的判斷,限定特定 hostname 才會依照使用者 IP 位置轉址。

<IfModule mod_geoip.c>
        GeoIPEnable On
        <IfModule mod_rewrite.c>
                RewriteEngine On
                RewriteCond %{HTTP_HOST} .
                RewriteCond %{HTTP_HOST} ^www\.example\.com$
                RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CN$
                RewriteRule ^(.*)$ http://www.example.com.cn$1 [L]
        </IfModule>
</IfModule>


參考資料:

2014年2月20日 星期四

[Linux] 使用 MAXMIND GeoLite2 Free 進行 Offline 查詢 IP 與 Country 和 City 對應 @ Ubuntu 12.04

使用 MAXMIND DB 進行 Offline 查詢 IP 與 Country 和 City 對應

雖然網路上還有不少可以線上查詢的服務,將 IP 轉成地區資訊,如:

$ curl ipinfo.io/8.8.8.8
{
  "ip": "8.8.8.8",
  "hostname": "google-public-dns-a.google.com",
  "city": null,
  "region": null,
  "country": "US",
  "loc": "38.0000,-97.0000",
  "org": "AS15169 Google Inc."
}


不過,大多都有查詢次數的限制,所以,自己架一個來處理吧,在此就挑選 MAXMIND GeoLite2 Free 來使用,其中 FREE 版本就只提供查詢 Country 跟 City 而已。

以 GeoLite2-City.mmdb 為例:

<?php

$target_ip = isset( $_REQUEST['ip'] ) && !empty($_REQUEST['ip']) ? $_REQUEST['ip'] : ( isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL ) ;
// $target_ip = '8.8.8.8';

require( 'MaxMind/Db/Reader.php' );
require( 'MaxMind/Db/Reader/Decoder.php' );
require( 'MaxMind/Db/Reader/InvalidDatabaseException.php' );
require( 'MaxMind/Db/Reader/Metadata.php' );

$reader = new MaxMind\Db\Reader('/path/GeoLite2-City.mmdb');
$record = $reader->get($target_ip);
$reader->close();
echo "<pre>";
print_r( $record );
echo "</pre>";


其中 MaxMind 程式碼可在 github.com/maxmind/MaxMind-DB-Reader-php 下載,此外,在 Ubuntu apt-get 上也有 php5-geoip - GeoIP module for php5 可安裝。

查詢 8.8.8.8:

Array
(
    [continent] => Array
        (
            [code] => NA
            [geoname_id] => 6255149
            [names] => Array
                (
                    [de] => Nordamerika
                    [en] => North America
                    [es] => Norteamérica
                    [fr] => Amérique du Nord
                    [ja] => 北アメリカ
                    [pt-BR] => América do Norte
                    [ru] => Северная Америка
                    [zh-CN] => 北美洲
                )

        )

    [country] => Array
        (
            [geoname_id] => 6252001
            [iso_code] => US
            [names] => Array
                (
                    [de] => USA
                    [en] => United States
                    [es] => Estados Unidos
                    [fr] => États-Unis
                    [ja] => アメリカ合衆国
                    [pt-BR] => Estados Unidos
                    [ru] => США
                    [zh-CN] => 美国
                )

        )

    [location] => Array
        (
            [latitude] => 38
            [longitude] => -97
        )

    [registered_country] => Array
        (
            [geoname_id] => 6252001
            [iso_code] => US
            [names] => Array
                (
                    [de] => USA
                    [en] => United States
                    [es] => Estados Unidos
                    [fr] => États-Unis
                    [ja] => アメリカ合衆国
                    [pt-BR] => Estados Unidos
                    [ru] => США
                    [zh-CN] => 美国
                )

        )

)


查詢台灣IP:

Array
(
    [city] => Array
        (
            [geoname_id] => 1668341
            [names] => Array
                (
                    [de] => Taipeh
                    [en] => Taipei
                    [es] => Taipéi
                    [fr] => Taipei
                    [ja] => 台北市
                    [pt-BR] => Taipé
                    [ru] => Тайбэй
                    [zh-CN] => 台北市
                )

        )

    [continent] => Array
        (
            [code] => AS
            [geoname_id] => 6255147
            [names] => Array
                (
                    [de] => Asien
                    [en] => Asia
                    [es] => Asia
                    [fr] => Asie
                    [ja] => アジア
                    [pt-BR] => Ásia
                    [ru] => Азия
                    [zh-CN] => 亚洲
                )

        )

    [country] => Array
        (
            [geoname_id] => 1668284
            [iso_code] => TW
            [names] => Array
                (
                    [de] => Republik China
                    [en] => Taiwan
                    [es] => Taiwán
                    [fr] => Taïwan
                    [ja] => 中華民国
                    [pt-BR] => Taiwan
                    [ru] => Тайвань
                    [zh-CN] => 台湾
                )

        )

    [location] => Array
        (
            [latitude] => 25.0392
            [longitude] => 121.525
            [time_zone] => Asia/Taipei
        )

    [registered_country] => Array
        (
            [geoname_id] => 1668284
            [iso_code] => TW
            [names] => Array
                (
                    [de] => Republik China
                    [en] => Taiwan
                    [es] => Taiwán
                    [fr] => Taïwan
                    [ja] => 中華民国
                    [pt-BR] => Taiwan
                    [ru] => Тайвань
                    [zh-CN] => 台湾
                )

        )

    [subdivisions] => Array
        (
            [0] => Array
                (
                    [geoname_id] => 7280290
                    [names] => Array
                        (
                            [de] => Taipeh
                            [en] => Taipei
                            [es] => Taipéi
                            [ja] => 台北市
                            [pt-BR] => Taipé
                            [ru] => Тайбэй
                        )

                )

        )

)