I have an R script that gets the public IP by
system("curl ifconfig.me",intern = T )
and then writes/appends it in a CSV file
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.
However, i will be running it in an small raspberry Zero and the installation of R is almost 500MB
is it possible to do this with bash?
The output should create or append a CSV file with (time and public IP as strings). If the internet is not reachable , "Internet not reachable" should be output. It doesn't necessarily have to do curl ifconfig.me
to check for internet connectivity . Checking for ping at 8.8.8.8
would be also an option. However it should output the public IP.
Thanks
CodePudding user response:
#!/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.
CodePudding user response:
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
- Obviously, "Internet unreachable" means "icanhazip.com unreachable". Failing to
ifconfig.me
, and/orping -c 1 -W 3 google.com
to log connectivity, but not IP, may be worthwhile to reduce maintenance of an embedded device. - I might even use a 5 second time out (instead of 3), for very slow connections, like bad satellite, proxies, etc.
${msg:-Unkown}
replaces an empty response withUnkown
.- You can change the date format:
man date
. - Add
2>/dev/null
to curl if you don't want cron to log errors it may produce (eg if internet is down). - More info on checking internet connectivity from the shell: https://unix.stackexchange.com/questions/190513/shell-scripting-proper-way-to-check-for-internet-connectivity