[英]bash: output/write/append a csv file with timestamp and public IP
I have an R script that gets the public IP by我有一个 R 脚本,它通过以下方式获得公众 IP
system("curl ifconfig.me",intern = T )
and then writes/appends it in a CSV file然后将其写入/附加到 CSV 文件中
write.table(data.frame(start.script=start.time, runtime=round(Sys.time()-start.time,4), ip=myip), append = T, file = "/home/eic/ip.report.csv", row.names = F,sep = ",", col.names = !file.exists("/home/eic/ip.report.csv"))
the script runs with cron every minute.该脚本每分钟与 cron 一起运行。
However, i will be running it in an small raspberry Zero and the installation of R is almost 500MB但是,我将在一个小树莓派零中运行它,R 的安装将近 500MB
is it possible to do this with bash?可以用 bash 做到这一点吗?
The output should create or append a CSV file with (time and public IP as strings). output 应该创建或 append 一个 CSV 文件(时间和公共 IP 作为字符串)。 If the inte.net is not reachable, "Inte.net not reachable" should be output. It doesn't necessarily have to do
curl ifconfig.me
to check for inte.net connectivity.如果无法访问 inte.net,“Inte.net not reachable”应为 output。它不一定必须执行
curl ifconfig.me
来检查 inte.net 连接。 Checking for ping at 8.8.8.8
would be also an option.在
8.8.8.8
检查 ping 也是一个选项。 However it should output the public IP.但是它应该是 output 公共 IP。
Thanks谢谢
#!/bin/bash
ip=$(curl --max-time 2 ifconfig.me 2>/dev/null) #Curl outputs some data on stderr. 2>/dev/null will remove that
hasInternet=$? #will be 0 if there was no error, make sure this line is directly after the curl line
curdate=$(date)
csvfile="file.csv" #right now this is a relative path to your working directory. For cron maybe better to use a absolute path
if [ $hasInternet -eq 0 ]; then
echo "${curdate},${ip}" >> $csvfile #>> will add a new line to the file
else
echo "${curdate},No internet" >> $csvfile
fi
I think this is a good start for your script.我认为这是您脚本的良好开端。 Might not be exactly as your original was, but I think you should be able to make the necessary changes.
可能与您原来的不完全一样,但我认为您应该能够进行必要的更改。
msg=$(curl -s --max-time 3 icanhazip.com) ||
msg='Internet unreachable'
echo "$(date '+%Y-%m-%d %T %Z'),${msg:-Unkown}" >> /home/eic/ip.report.csv
Each line will look like:每行看起来像:
2022-02-21 14:59:59,12.123.123.12 UTC
ifconfig.me
, and/or ping -c 1 -W 3 google.com
to log connectivity, but not IP, may be worthwhile to reduce maintenance of an embedded device. ifconfig.me
和/或ping -c 1 -W 3 google.com
无法记录连接,但 IP 可能值得减少嵌入式设备的维护。${msg:-Unkown}
replaces an empty response with Unkown
. ${msg:-Unkown}
将空响应替换为Unkown
。man date
.man date
。2>/dev/null
to curl if you don't want cron to log errors it may produce (eg if inte.net is down).2>/dev/null
添加到 curl。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.