我正在尝试编写一个脚本,该脚本将检测何时有人通过 DHCP 加入我的网络,然后通过电子邮件向我发送详细信息。我遇到的问题是解析循环中的纪元时间。
我省略了获取租赁信息、错误检查、比较和发送电子邮件的代码,因为这不是问题。
租赁信息文件的格式如下:
epoch time MAC address IP Address Hostname DeviceID
4476705071 11:11:11:11:11:11 111.111.111.111 device1 *
7956915742 22:22:22:22:22:22 222.222.222.222 device2 *
我使用以下代码引用该文件:
#! /bin/bash
LEASELEN=21600 # SET THE LEASE LENGTH TO 6 HOURS TO DETERMINE START OF LEASE
arrEND=($(cat /usr/local/bin/dhcp/leases.new | awk '{print $1}')) # LEASE EXPIRY IN EPOCH
arrMAC=($(cat /usr/local/bin/dhcp/leases.new | awk '{print $2}')) # MAC ADDRESS
arrIP=($(cat /usr/local/bin/dhcp/leases.new | awk '{print $3}')) # IP ADDRESS
arrHOST=($(cat /usr/local/bin/dhcp/leases.new | awk '{print $4}')) # HOSTNAME
echo 'Current and New connections to the network via DHCP:'
for ((i=0;i<${#arrIP[@]};i++)) # ITERATE FROM 0 TO TOTAL NUMBER OF ENTRIES
do
arrSTART=$(expr ${arrEND[$i]} - $LEASELEN) # CALCULATE LEASE START FROM LEASE END
arrSTARTH=`date -d @${arrSTART[$i]} +"%Y-%m-%d %T"` # CONVERT EPOCH TO HUMAN-READABLE
echo "\""${arrHOST[$i]}"\" started using "${arrIP[$i]}" on "${arrSTARTH[$i]}" with MAC "${arrMAC[$i]}"." #OUTPUT
done
exit 0
输出是:
Current and New connections to the network via DHCP:
date: invalid date ‘@4476683471’
"device1" started using 111.111.111.111 on with MAC 11:11:11:11:11:11.
date: invalid date ‘@’
"device2" started using 222.222.222.222 on with MAC 22:22:22:22:22:22.
我怀疑部分问题是我把时间设定得太晚了。因为如果我在租赁文件的开头添加另外 2 行来使其:
epoch time MAC address IP Address Hostname DeviceID
1465374613 00:b0:d0:01:32:86 192.168.0.1 pre-device1 *
1465374820 00:00:00:00:00:00 0.0.0.0 pre-device2 *
4476705071 11:11:11:11:11:11 111.111.111.111 device1 *
7956915742 22:22:22:22:22:22 222.222.222.222 device2 *
我在第一个结果中得到了日期,但之后没有日期。
输出:
Current and New connections to the network via DHCP:
"pre-device1" started using 192.168.0.1 on 2016-06-08 04:30:13 with MAC 00:b0:d0:01:32:86.
date: invalid date ‘@’
"pre-device2" started using 0.0.0.0 on with MAC 00:00:00:00:00:00.
date: invalid date ‘@’
"device1" started using 111.111.111.111 on with MAC 11:11:11:11:11:11.
date: invalid date ‘@’
"device2" started using 222.222.222.222 on with MAC 22:22:22:22:22:22.
知道我做错了什么吗?
答案1
你为什么不用gawk
这个呢?转换时间与时间:
awk 'BEGIN{PROCINFO["strftime"]="%s"} { print $4, "started using", $3, "on", strftime("%Y-%m-%d %T",$1), "with MAC", $2"."}' /usr/local/bin/dhcp/leases.new
输出:
device1 started using 111.111.111.111 on 2111-11-11 18:11:11 with MAC 11:11:11:11:11:11.
device2 started using 222.222.222.222 on 2222-02-22 23:22:22 with MAC 22:22:22:22:22:22.