LoginSignup
0
0

More than 1 year has passed since last update.

『debian linux』でサーバーのシステム時間とハードウェアクロックの時間を暫定的にセットする。 

Posted at

目的

止む得ない場合に時間を隣やポートが開いているのwebサーバから取得し設定する。

方法

  • システム標準ツールのみで動作する。
  • http,httpsの通信で取得する。

使用するツール

  • perl
  • wget
  • date
  • hwclock
    ※debianlinux10では標準に入っている。

処理フロー

  1. "wget"でhttpのresponse内の時間を取得する。
HTTP request sent, awaiting response...
  HTTP/1.1 301 Moved Permanently
  Location: http://www.google.com/
  (...省略...)
  Date: Tue, 10 Jan 2023 23:04:55 GMT
  1. "perl"で日付フォーマットを処理しコマンドパラメータフォーマットに変換する。
  2. "date"で日付をセットする。(epoch時間を使用)
/usr/bin/date -d '@1673390556'
  1. "hwclock"で日付をセットする。
/sbin/hwclock --set --date "11 Jan 2023 08:17:30"

コード

#!/usr/bin/env perl

use strict;
use utf8;
use warnings;
use Time::Piece;

my @url_a = ("http://www.google.com","http://www.yahoo.co.jp");

#regex for date in response header;
my $date_re = "Date\: [a-zA-Z]*, ([0-9]{2}) ([a-zA-Z]*) ([0-9]{4}) *([0-9]{2})\:([0-9]{2})\:([0-9]{2})";

sub get_date_fmt_str_f($){
  my $url_s = shift;
  #Change wget output from "stderr" to "stdout". with option "-o - ";
  my $result_s = `/usr/bin/wget -o - -S --spider $url_s 2>/dev/null`;
  if ( $result_s =~ m/$date_re/ ){
    #my ($day,$mon,$year,$hour,$min,$sec) = ($1,$2,$3,$4,$5,$6);
    return "$3 $2 $1 $4:$5:$6";
  }
  return "";
}

#set hardware clock;
sub set_hwclock_f($){
  my $gt = shift;
  my $lt = localtime($gt->epoch);
  my $hwclock_s = $lt->strftime("%d %b %G %H:%M:%S");
  #print '#/sbin/hwclock --set --date "11 Jan 2023 08:17:30"' . "\r\n";
  my $hwclock_e = '/sbin/hwclock --set --date "' . $hwclock_s . '"';
  print $hwclock_e . "\r\n";
  #exec $hwclock_e;
  `$hwclock_e`;
}

#set software clock;
sub set_date_f($){
  my $gt = shift;
  my $date_e = "/usr/bin/date -s '@" . $gt->epoch . "'";
  #print "#/usr/bin/date -d '@1673390556'r\n";
  print $date_e . "\r\n";
  #exec $date_e;
  `$date_e`;
}

foreach my $url_s ( @url_a ) {
  my $ts = &get_date_fmt_str_f($url_s);
  if( $ts ne "" ){
    my $gt = Time::Piece->strptime($ts, '%Y %b %d %H:%M:%S');
    &set_hwclock_f($gt);
    &set_date_f($gt);
    exit(0);
  }
}

確認を行う場合は以下の行をコメントアウトします。

  `$hwclock_e`;
  `$date_e`;

※UTCからlocaltimeの変換は必要に応じて調整をお願いします。
※止むを得ない場合にご使用しますので、ご使用には十分な注意をお願いいたします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0