MySQLのデータサンプルとして郵便番号のデータを入れる

日本郵便:郵便番号データの説明

日本郵便
こういう実用性の高いデータを公開してくれているのは
本当にありがたいですよね。

サンプルデータ取得

$ wget http://www.post.japanpost.jp/zipcode/dl/kogaki/lzh/ken_all.lzh

lzhなのでlhaとか必要

全国の郵便番号のデータをダウンロード。
スペック低いようだったら各都道府県のに限定してもいいかも。

$ lha x ken_all.lzh
$ nkf -g ken_all.csv 
Shift_JIS (CR)

Shift JISなのでUTF-8に変換。

$ nkf -w --overwrite ken_all.csv
$ nkf -g ken_all.csv
UTF-8 (CR)

MySQLで読み込む

参考:MySQL に郵便番号データをインポート

mysql> CREATE DATABASE yuubin CHARACTER SET utf8; 
mysql> use yuubin;
mysql> CREATE TABLE zipcode (
PublicCode char(5) NOT NULL,
OldZipCode char(5) NOT NULL,
ZipCode char(7) NOT NULL,
PrefectureKana varchar(10),
CityKana varchar(100),
TownKana varchar(100),
Prefecture varchar(10),
City varchar(200),
Town varchar(200),
TownDivideFlg tinyint(1),
KoazaBanchiFlg tinyint(1),
TyoumeFlg tinyint(1),
HasSomeTownFlg tinyint(1),
UpdateState tinyint(1),
UpdateReson tinyint(1),
PRIMARY KEY (ZipCode)
);
mysql> LOAD DATA INFILE './ken_all.csv' IGNORE INTO TABLE zipcode FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"';
mysql> 
mysql> SELECT * FROM zipcode LIMIT 10 ;
+------------+------------+---------+--------------------+--------------------------+------------------------------------------+------------+-----------------+--------------------------------------+---------------+----------------+-----------+----------------+-------------+-------------+
| PublicCode | OldZipCode | ZipCode | PrefectureKana     | CityKana                 | TownKana                                 | Prefecture | City            | Town                                 | TownDivideFlg | KoazaBanchiFlg | TyoumeFlg | HasSomeTownFlg | UpdateState | UpdateReson |
+------------+------------+---------+--------------------+--------------------------+------------------------------------------+------------+-----------------+--------------------------------------+---------------+----------------+-----------+----------------+-------------+-------------+
| 01102      | 001        | 0010000 | ホッカイドウ       | サッポロシキタク         | イカニケイサイガナイバアイ               | 北海道     | 札幌市北区      | 以下に掲載がない場合                 |             0 |              0 |         0 |              0 |           0 |           0 | 
| 01102      | 001        | 0010010 | ホッカイドウ       | サッポロシキタク         | キタ10ジョウニシ(1-4チョウメ)            | 北海道     | 札幌市北区      | 北十条西(1〜4丁目)               |             1 |              0 |         1 |              0 |           0 |           0 | 
| 01102      | 001        | 0010011 | ホッカイドウ       | サッポロシキタク         | キタ11ジョウニシ(1-4チョウメ)            | 北海道     | 札幌市北区      | 北十一条西(1〜4丁目)             |             1 |              0 |         1 |              0 |           0 |           0 | 
| 01102      | 001        | 0010012 | ホッカイドウ       | サッポロシキタク         | キタ12ジョウニシ(1-4チョウメ)            | 北海道     | 札幌市北区      | 北十二条西(1〜4丁目)             |             1 |              0 |         1 |              0 |           0 |           0 | 
| 01102      | 001        | 0010013 | ホッカイドウ       | サッポロシキタク         | キタ13ジョウニシ(1-4チョウメ)            | 北海道     | 札幌市北区      | 北十三条西(1〜4丁目)             |             1 |              0 |         1 |              0 |           0 |           0 | 
+------------+------------+---------+--------------------+--------------------------+------------------------------------------+------------+-----------------+--------------------------------------+---------------+----------------+-----------+----------------+-------------+-------------+
10 rows in set (0.00 sec)
mysql> 
mysql> SELECT CityKana FROM zipcode WHERE ZipCode = 2480006;
+-----------------+
| CityKana        |
+-----------------+
| カマクラシ      |
+-----------------+
1 row in set (0.17 sec)

mysql> 

という感じでSQLのコマンドの練習とかに使える感じです。

tmux入れるときに色々エラーとか出たりしたのでその時のメモ

環境はこんな感じ

OS: CentOS 5.2
RPM: libevent-1.1a-3.2.1 インストール済み

yum install tmux

$ yum install tmux
Loaded plugins: rhnplugin
Excluding Packages in global exclude list
Finished
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package tmux.x86_64 0:1.6-1.el5.rf set to be updated
--> Processing Dependency: libevent-1.4.so.2()(64bit) for package: tmux
--> Finished Dependency Resolution
tmux-1.6-1.el5.rf.x86_64 from rpmforge has depsolving problems
  --> Missing Dependency: libevent-1.4.so.2()(64bit) is needed by package tmux-1.6-1.el5.rf.x86_64 (rpmforge)
Error: Missing Dependency: libevent-1.4.so.2()(64bit) is needed by package tmux-1.6-1.el5.rf.x86_64 (rpmforge)
 You could try using --skip-broken to work around the problem
 You could try running: package-cleanup --problems
                        package-cleanup --dupes
                        rpm -Va --nofiles --nodigest
The program package-cleanup is found in the yum-utils package.

ふええ〜
仕方ないのでlibeventをsourceでインストール

libevent

$ wget http://downloads.sourceforge.net/project/levent/libevent/libevent-2.0/libevent-2.0.19-stable.tar.gz
$ tar xzf libevent-2.0.19-stable.tar.gz
$ cd libevent-2.0.19-stable
$ ./configure
$ make -j8
$ make install

$ # ls /usr/local/lib
libdrac.a              libevent_core-2.0.so.5      libevent_extra-2.0.so.5.1.7    libevent_openssl.a              libevent_pthreads.la
libevent-2.0.so.5      libevent_core-2.0.so.5.1.7  libevent_extra.a               libevent_openssl.la             libevent_pthreads.so
libevent-2.0.so.5.1.7  libevent_core.a             libevent_extra.la              libevent_openssl.so             pkgconfig
libevent.a             libevent_core.la            libevent_extra.so              libevent_pthreads-2.0.so.5
libevent.la            libevent_core.so            libevent_openssl-2.0.so.5      libevent_pthreads-2.0.so.5.1.7
libevent.so            libevent_extra-2.0.so.5     libevent_openssl-2.0.so.5.1.7  libevent_pthreads.a

$ ldconfig -p でlibeventが出てくればOK、出てこなければ
$ echo /usr/local/lib >> /etc/ld.so.conf
$ ldconfig -p して表示されればOK

サーバで ldconfig 打つ怖さ

tmux

$ wget http://downloads.sourceforge.net/project/tmux/tmux/tmux-1.6/tmux-1.6.tar.gz
$ tar tmux-1.6.tar.gz
$ cd tmux-1.6
$ ./configure
$ make -j8 

...
server.o: In function `server_start':
server.c:(.text+0x223): undefined reference to `event_reinit'
status.o: In function `status_job_callback':
status.c:(.text+0x27bb): undefined reference to `evbuffer_get_length'
status.c:(.text+0x27f2): undefined reference to `evbuffer_pullup'
tty-keys.o: In function `tty_keys_next':
tty-keys.c:(.text+0x452): undefined reference to `evbuffer_pullup'
tty-keys.c:(.text+0x46a): undefined reference to `evbuffer_get_length'
window.o: In function `window_pane_read_callback':
window.c:(.text+0x403f): undefined reference to `evbuffer_get_length'
window.c:(.text+0x408b): undefined reference to `evbuffer_pullup'
window.c:(.text+0x40c4): undefined reference to `evbuffer_get_length'
collect2: ld はステータス 1 で終了しました
make: *** [tmux] エラー 1

エラー出る。さっきインストールしたlibeventのライブラリ読み込ませる

$ ./configure LDFLAGS=-L/usr/local/lib/
$ make -j8

エラー出ない

$ make install

インストールできた

という感じ。

WWW::MechanizeでHTTPSとやり取りするとき

オレオレ証明書を使っていると

Error GETing https://example.com/: Can't connect to example.com:443 (certificate verify failed)

こんなエラーが出る。

WWW::MechanizeはLWP::UserAgent呼び出しているので

my $mech = WWW::Mechanize->new(ssl_opts => { verify_hostname => 0 });

こうやって書けば無視してくれるってなんか英語で書いてあった。

よく忘れるのでメモ。

WWW::Mechanizeでファイルダウンロードする時にLWP::Simpleのgetstoreみたいに楽できないかなって思ったら

https://metacpan.org/module/WWW::Mechanize::Cookbook

Cookbookに

$mech->get( "http://www.cpan.org/src/stable.tar.gz",
                ":content_file" => "stable.tar.gz" );

って書いてあってそのまま書いたらダウンロードできた。
これでセッション管理されてるムフフなメトリクス画像も簡単に手に入れられる。

Jesse Vincent++

OpenVPNで外出先のMBAからさくらVPS通して自宅サーバにつなげる環境をつくるの巻

自宅 - さくらVPS - Macbook Air

で繋いで、自宅のファイルサーバに置いてある音楽ファイルを
外出先のMBAiTunes通して聞けないかなーと思ったんですけど
ちと重くて無理っぽかった。

OpenVPN、構築メモ。

参考元
http://www.openvpn.jp/howto.html

オフィシャル最強です。


環境としては

 MBA(192.168.10.1)
 |
 OpenVPN (10.8.0.6) 
 |
 sakura VPS(Global IP)
 OpenVPN (10.8.0.1)
 |
 OpenVPN (10.8.0.10)
 |
 自宅サーバ(192.168.200.3)

こんな感じで繋ぎます。OpenVPN専用のセグメントをつくり
そのセグメントを通してやりとりを行うって感じですね。

sakura vps

中継地点となるVPSOpenVPNの設定をします。

まずはダウンロードしてくる。

$ cd /usr/local/src
$ wget http://swupdate.openvpn.org/community/releases/openvpn-2.2.2.tar.gz
$ tar xzf openvpn-2.2.2.tar.gz
$ cd openvpn-2.2.2 ; pwd
$ ./configure
configure: error: Or try ./configure --disable-lzo

lzoで圧縮して通信する場合は必要

$ sudo yum install lzo-devel.x86_64
$ ./configure
$ make 
$ sudo make install

インストール完了。

/etc/openvpnディレクトリを作成して
設定ファイルをコピー。

$ mkdir /etc/openvpn
$ ls -ld /etc/openvpn
$ cp -ip sample-config-files/server.conf /etc/openvpn/
$ cp -ip sample-scripts/openvpn.init /etc/init.d/openvpn


鍵ファイルとかを作成する。

$ cd /usr/local/src/openvpn-2.2.2/easy-rsa/1.0
$ . ./vars
$ ./clean-all
$ ./build-ca 
Generating a 1024 bit RSA private key
.....++++++
..........................++++++
writing new private key to 'ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [KG]:JP
State or Province Name (full name) [NA]:
Locality Name (eg, city) [BISHKEK]:
Organization Name (eg, company) [OpenVPN-TEST]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address [me@myhost.mydomain]:
$ 

ここで設定した内容と、後述する鍵ファイルの内容が違っていたら
ファイル生成されません。(当たり前)

サーバ用のkeyを作成。

$ ./build-key server
Generating a 1024 bit RSA private key
...............................++++++
.............++++++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [KG]:JP
State or Province Name (full name) [NA]:
Locality Name (eg, city) [BISHKEK]:
Organization Name (eg, company) [OpenVPN-TEST]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:server
Email Address [me@myhost.mydomain]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/local/src/openvpn-2.2.2/easy-rsa/1.0/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'JP'
stateOrProvinceName   :PRINTABLE:'NA'
localityName          :PRINTABLE:'BISHKEK'
organizationName      :PRINTABLE:'OpenVPN-TEST'
commonName            :PRINTABLE:'server'
emailAddress          :IA5STRING:'me@myhost.mydomain'
Certificate is to be certified until Jun 20 16:21:05 2022 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated


client1用のkeyを作成

$ ./build-key client1
Generating a 1024 bit RSA private key
.........++++++
..++++++
writing new private key to 'client1.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [KG]:JP
State or Province Name (full name) [NA]:
Locality Name (eg, city) [BISHKEK]:
Organization Name (eg, company) [OpenVPN-TEST]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:client1
Email Address [me@myhost.mydomain]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/local/src/openvpn-2.2.2/easy-rsa/1.0/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'JP'
stateOrProvinceName   :PRINTABLE:'NA'
localityName          :PRINTABLE:'BISHKEK'
organizationName      :PRINTABLE:'OpenVPN-TEST'
commonName            :PRINTABLE:'client1'
emailAddress          :IA5STRING:'me@myhost.mydomain'
Certificate is to be certified until Jun 20 16:21:40 2022 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated


client2用のkeyを作成。

$ ./build-key client2
Generating a 1024 bit RSA private key
...........................++++++
......++++++
writing new private key to 'client2.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [KG]:JP
State or Province Name (full name) [NA]:
Locality Name (eg, city) [BISHKEK]:
Organization Name (eg, company) [OpenVPN-TEST]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:client2
Email Address [me@myhost.mydomain]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/local/src/openvpn-2.2.2/easy-rsa/1.0/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'JP'
stateOrProvinceName   :PRINTABLE:'NA'
localityName          :PRINTABLE:'BISHKEK'
organizationName      :PRINTABLE:'OpenVPN-TEST'
commonName            :PRINTABLE:'client2'
emailAddress          :IA5STRING:'me@myhost.mydomain'
Certificate is to be certified until Jun 20 16:21:54 2022 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

$ 
$ ./build-dh
Generating DH parameters, 1024 bit long safe prime, generator 2
This is going to take a long time
......................................................................................+............................+..................................................+..........................................+.........................+...............................................................................................+...................+.....................................................+............+....+.....................................................................................................+..............................+....................................+...........................................+.....+.......................+........................+..........+..........................................+..................++*++*++*
$ 
$ 
$ ls -a keys/
.   ca.crt  client1.crt  client1.key  client2.csr  dh1024.pem  serial      server.csr
..  ca.key  client1.csr  client2.crt  client2.key  index.txt   server.crt  server.key
$ 

こんな感じでファイルができる。
できたファイルをコピーする。

$ cd kyes/
$ cp -ip ca.crt server.crt server.key dh1024.pem /etc/openvpn/


$ grep -E '^[a-z]' /etc/openvpn/server.conf 
port 1194
proto udp
dev tun
ca ca.crt
cert server.crt
key server.key  # This file should be kept secret
dh dh1024.pem
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt
keepalive 10 120
comp-lzo
persist-key
persist-tun
status openvpn-status.log
verb 3
client-to-client


$ openvpn /etc/openvpn/server.conf 
Mon Jul  2 19:05:22 2012 OpenVPN 2.2.2 x86_64-unknown-linux-gnu [SSL] [LZO2] [EPOLL] [eurephia] built on Jun 23 2012
Mon Jul  2 19:05:22 2012 NOTE: OpenVPN 2.1 requires '--script-security 2' or higher to call user-defined scripts or executables
Mon Jul  2 19:05:22 2012 Diffie-Hellman initialized with 1024 bit key
Mon Jul  2 19:05:22 2012 WARNING: file 'server.key' is group or others accessible
Mon Jul  2 19:05:22 2012 TLS-Auth MTU parms [ L:1542 D:138 EF:38 EB:0 ET:0 EL:0 ]
Mon Jul  2 19:05:22 2012 Socket Buffers: R=[124928->131072] S=[124928->131072]
Mon Jul  2 19:05:22 2012 ROUTE default_gateway=219.94.244.1
Mon Jul  2 19:05:22 2012 TUN/TAP device tun0 opened
Mon Jul  2 19:05:22 2012 TUN/TAP TX queue length set to 100
Mon Jul  2 19:05:22 2012 /sbin/ifconfig tun0 10.8.0.1 pointopoint 10.8.0.2 mtu 1500
Mon Jul  2 19:05:22 2012 /sbin/route add -net 10.8.0.0 netmask 255.255.255.0 gw 10.8.0.2
Mon Jul  2 19:05:22 2012 Data Channel MTU parms [ L:1542 D:1450 EF:42 EB:135 ET:0 EL:0 AF:3/1 ]
Mon Jul  2 19:05:22 2012 UDPv4 link local (bound): [undef]:1194
Mon Jul  2 19:05:22 2012 UDPv4 link remote: [undef]
Mon Jul  2 19:05:22 2012 MULTI: multi_init called, r=256 v=256
Mon Jul  2 19:05:22 2012 IFCONFIG POOL: base=10.8.0.4 size=62
Mon Jul  2 19:05:22 2012 IFCONFIG POOL LIST
Mon Jul  2 19:05:22 2012 client1,10.8.0.4
Mon Jul  2 19:05:22 2012 client2,10.8.0.8
Mon Jul  2 19:05:22 2012 Initialization Sequence Completed

起動できることを確認


sakura VPSは今回中継役となるため、パケットをフォワードしたいので

$ /etc/sysctl.conf
net.ipv4.ip_forward = 1
$ sysctl -p

$ iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

な感じでフォワードを有効化しておく必要がある。

自宅サーバ(Ubuntu)

sakura VPSで作成したファイルをscpなどでコピーしてくる。

$ apt-get install openvpn
$
$ ls -a /etc/openvpn 
.  ..  ca.crt  client2.conf  client2.crt  client2.key
$
$ /etc/init.d/openvpn start
$ 


sample-config-files/client.confを参考にclient2.confを作成

client2.conf

client
dev tun
proto udp
remote REMOTESERVER PORT
resolv-retry infinite
nobind
persist-key
persist-tun
ca /etc/openvpn/ca.crt
cert /etc/openvpn/client2.crt
key /etc/openvpn/client2.key
comp-lzo
verb 3


この状態で ping が 10.8.0.1 に届けばVPNは開通していることになります。

MBA

Tunnelblick を使ってます。

わたしの場合は、
~/Library/Application\ Support/Tunnelblick/Configurations/openvpn/
の中に、client2と同様のものを置いています。

この状態で接続して成功すればもう90%は完了しています。

$ ping -c 5 10.8.0.10                                                
PING 10.8.0.10 (10.8.0.10): 56 data bytes
64 bytes from 10.8.0.10: icmp_seq=0 ttl=64 time=31.136 ms
64 bytes from 10.8.0.10: icmp_seq=1 ttl=64 time=31.349 ms
64 bytes from 10.8.0.10: icmp_seq=2 ttl=64 time=30.361 ms
64 bytes from 10.8.0.10: icmp_seq=3 ttl=64 time=31.680 ms
64 bytes from 10.8.0.10: icmp_seq=4 ttl=64 time=30.396 ms

--- 10.8.0.10 ping statistics ---
5 packets transmitted, 5 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 30.361/30.984/31.680/0.524 ms

MBA -> sakura VPS -> 自宅サーバ
で疎通が取れることを確認。

$ ping -c 5 10.8.0.6
PING 10.8.0.6 (10.8.0.6) 56(84) bytes of data.
64 bytes from 10.8.0.6: icmp_req=1 ttl=64 time=35.4 ms
64 bytes from 10.8.0.6: icmp_req=2 ttl=64 time=30.9 ms
64 bytes from 10.8.0.6: icmp_req=3 ttl=64 time=34.6 ms
64 bytes from 10.8.0.6: icmp_req=4 ttl=64 time=30.7 ms
64 bytes from 10.8.0.6: icmp_req=5 ttl=64 time=32.1 ms

--- 10.8.0.6 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4002ms
rtt min/avg/max/mdev = 30.776/32.778/35.415/1.905 ms

自宅サーバ -> sakura VPS -> MBA

で疎通が取れることを確認。
無事OpenVPNVPNが接続できたことになりました。

以上、カジュアルですが、自分用まとめです。

KVMのホスト追加時にホスト設定用のXMLファイルたくさん書くのが億劫だったのでcsvファイル読み込んでいっぺんにいっぱいXMLファイルつくるスクリプト書いた

https://github.com/kenjiskywalker/make-kvm-xml

最近痴呆気味なので使い方はREADMEに全部書いた。
Perl素人だけど日々のこういうところをPerl使って楽にしていきたい。

Perlペロペロ(^ω^)

ZABBIXでスクリーンつくるのにXMLファイルごにょごにょするの大変なのでcsvファイル読み込んでスクリーン用XMLファイルつくってくれるスクリプト書いた

https://github.com/kenjiskywalker/make-zabbix-screen

もしかしたら2系だと全然違うっぽいので1.8系限定ということで。
Perl素人だけど日々のこういうところをPerl使って楽にしていきたい。

使い方は簡単で、make_screen.csvの中身をREADMEを読みながら設定箇所書き換えて
$ perl make_screen.pl するだけでXMLファイルができます。

make_screen.csvの第一フィールドがファイル名になっているのですが、
csvひとつで複数のXMLつくるようにはまだできていません。そのうちやります。

Perlペロペロ(^ω^)

[追記]
csvひとつで複数のXMLつくれるようにした。