http経由でntp serverに問い合わせて時刻合わせをする (Linux)

はじめに

企業内だと、firewallによって外部のntp serverに直接アクセスできない場合があります。ntp はUDP 123 port を使うため、proxy serverが許さないとproxy 越えは難しいようです。

実際には、ルータやスイッチングHUBが ntp server機能を持つ場合もあるのですが、ここではhttp経由でntp serviceにアクセスしてPCの時刻合わせを行うことを考えます。

http経由でのntp serviceの利用

NICTの日本標準時G のhttps/http を介してアクセスされる場合にPOSIX形式でタイムスタンプを返すURLが記載されています。これを利用します。

POSIX形式のページをダウンロードするにはRubyのnokogiri を用いました。

時刻合わせには Linuxの dateコマンドを用いました。これはsuper user権限(sudo)で実行します。

ruby のコード

ruby 1.9以降を用いています。

#!/usr/bin/env ruby1.9.3
# -*- coding: utf-8 -*-
#
# $Id$
=begin
Thanks: 

http://husky.mydns.jp/huskysmemo/2010/02/ntpproxy.html
=end

require "open-uri"
require "rubygems"
require "nokogiri"

url = "https://ntp-a1.nict.go.jp/cgi-bin/jst"

charset = nil
html = open(url, :proxy => 'http://proxy.server.url:PORT') do |f|
  charset = f.charset
  f.read
end
doc = Nokogiri::HTML.parse(html, nil, charset)
time = doc.css("body").text.gsub(/[\r\n]/,'').to_f

local_time = Time.at(time)

printf("%s\n", local_time.strftime("Local Time: %Y年%m月%d日%H時%M分%S秒"))

time_str = local_time.strftime("%m%d%H%M.%S")

system("date") # 現在のPCの時刻

puts command  = "date #{time_str}"
system(command) # 時刻あわせ

参考にしたページ

Adsense広告