使用 curl 或 wget 从路由器中的 http 标头设置日期和时间

使用 curl 或 wget 从路由器中的 http 标头设置日期和时间

此技术应该与 Ubuntu 上的类似或相同;尽管以下代码在路由器上不起作用。一种方法如下:

dateFromServer=$(curl -v --silent https://google.com/ 2>&1 \
 | grep Date | sed -e 's/< Date: //')
date +"%d%m%Y%H%M%S" -d "$dateFromServer"

结果是

'ate: 无效日期 '2018 年 5 月 12 日星期六 18:49:18 GMT

或从 HTTP 响应标头获取日期。 删除杂乱信息。 设置日期。

date -s `curl -I 'https://startpage.com/' 2>/dev/null | grep -i '^date:' | sed 's/^[Dd]ate: //g'`

我得到的结果如下:

@Heyzeus:/tmp/home/root# date -s `curl -I 'https://google.com/' 2>/dev/null | grep -i '^date:' | sed 's/^[Dd]ate: //g'` BusyBox v1.25.1 (2018-05-06 13:19:15 EDT) multi-call binary.

Usage: date [OPTIONS] [+FMT] [TIME]

Display time (using +FMT), or set time

[-s,--set] TIME Set time to TIME
-u,--utc Work in UTC (don't convert to local time)
-R,--rfc-2822 Output RFC-2822 compliant date string
-I[SPEC] Output ISO-8601 compliant date string SPEC='date' (default) for date only, 'hours', 'minutes', or 'seconds' for date and time to the indicated precision
-r,--reference FILE Display last modification time of FILE
-d,--date TIME Display TIME, not 'now'
-D FMT Use FMT for -d TIME conversion

Recognized TIME formats: hh:mm[:ss] [YYYY.]MM.DD-hh:mm[:ss] YYYY-MM-DD hh:mm[:ss] [[[[[YY]YY]MM]DD]hh]mm[.ss] 'date TIME' form accepts MMDDhhmm[[YY]YY][.ss] instead

其他

日期 -s“$(wget -qSO- --max-redirect=0 startpage.com 2>&1 | grep 日期:| cut -d' ' -f5-8)”

结果为:日期:无效日期‘2018 年 5 月 13 日 22:46:44’

前两个结果中提取的时间例如为:“2018 年 5 月 12 日星期六 18:49:18 GMT”,日期 -s 需要更像 2018-05-12 18:49:18 的时间,或者在“可识别的时间格式”下列出。

很接近了。但是“星期六”需要删除,月份需要用数字替换,然后正确排列;如果这些可以在一个终端命令中单独完成,那就太好了。

答案1

谢谢小枝

这是设置日期的替代方法 !!! [-s 选项]。打印出它检索的“日期”和设置的“日期”以供比较。

这在 AsusWRT / Merlin 上有效,唯一奇怪的是检索到的日期是“.... GMT”,日期实用程序设置了正确的时间,但将其更改为“... DST”环境将 TZ 设置为“GMT”

datetext=$(curl -I 'https://1.1.1.1/' 2>/dev/null | grep "Date:" |sed 's/Date: [A-Z][a-z][a-z], //g'| sed 's/\r//') ; echo "Date Retrieved = $datetext" ; echo -n "Date set = " ; date -s "$datetext" -D'%d %b %Y %T %Z'

相关内容