用于检查设备是否在线的脚本,如果不在线则执行某些操作

用于检查设备是否在线的脚本,如果不在线则执行某些操作

我正在构建一个用于 rtsp ffmpeg 捕获和 24/7 目的的 IP 摄像机服务器。唯一缺少的是检查摄像机连接的脚本,如果无法访问,则应触发另一个脚本来检查摄像机的在线状态,以便可以启动新的 ffmpeg 捕获过程。

我已经花了很多时间进行测试,但现在没有任何效果。因此,对于这项工作,我有三个脚本。第一个应该检查相机是否仍然可以访问,如果不是,则转到第二个:

#!/bin/sh
# record-ping_cam1.sh
# Check 24h if cam is alive, in case of error code 1 (offline) start record-waitfor_xxx.sh
#
IPCAM=192.168.xxx.xxx
ping -w 86400 -i2 $IPCAM 0>/dev/null
OFFLINE=$?
if [ $OFFLINE -eq 1 ]
then
  source /home/xxx/record-ping-waitfor_cam1.sh
fi

第二个应该检查是否可以再次访问,如果可以,则转到第三个:

#!/bin/sh
# record-ping-waitfor_cam1.sh
# Check if Cam is alive, if yes (exit code 0) then execute record-ping-reconnect_xxx.sh
#
# Ping with infinitive loop - as soon as reachable (exit code 0) then go on with record script
IPCAM=192.168.xxx.xxx
while true; do ping -c1 $IPCAM > /dev/null && break; done
ONLINE=$?
if [ $ONLINE -eq 0 ]
then
  source /home/xxx/record-ping-reconnect_cam1.sh
fi        

第三个启动新的 ffmpeg 进程并将 ffmpeg 和 ping PID 写入文件(稍后需要):

#!/bin/sh
# record-ping-reconnect_cam1.sh
# Record IPcam after any case of signal lost
#
# This will print the current date and time in a format appropriate for storage
STARTTIME=$(/bin/date +"%d.%m.%Y")-"("$(/bin/date +"%H").$(/bin/date +"%M")Uhr")"
#
## IP Camera Names ##
# Creating date stamps for each of the Cameras
CAM=Cam1_$STARTTIME
#
## Network and Local Storage Locations  ## #Trailing '/' is necessary here
RCDIR="/home/xxx/Reconnect/"
#
## Record Time per File sec ##
LENGTH="86400" # (24h)
#
## Record Settings ##
#
# wait until cam is ready to capture again
sleep 40s
# start capture this camsource
ffmpeg -v 0 -rtsp_transport tcp -i "rtsp://device:port/11" -vcodec copy -an -t $LENGTH $RCDIR$CAM1.mkv & echo $! > /home/xxx/Reconnect/PIDs/ffmpeg_cam1.pid
# start the ping routine, check the cam for connectivity
source /home/xxx/record-ping_cam1.sh & echo $! > /home/xxx/Reconnect/PIDs/ping_cam1.pid
exit

问题是......第一个脚本运行良好,但我在第二个脚本中遇到了麻烦。然后我用 fping 尝试了不同的事情,但没有运气。现在,在 while 循环中执行 ping 操作,它可以完美运行。但随后第一个脚本停止工作......这对我来说似乎很奇怪。

服务器是具有 Raspbian Stretch 的 RPI 3b+

答案1

好吧,明白了!在这种情况下似乎then没有else失败。现在它正在发挥作用。

# Ping in an infintive loop - as soon as reachable (exit code 0) then go on with record script
HOST=adress
ping -w 86400 -i2 $HOST 0>/dev/null
OFFLINE=$?
if [ $OFFLINE -eq 1 ]
then
  echo " " 
else
  bash /home/xxx/record-ping-waitfor_g-cam1.sh
fi

答案2

只是注释强调可以直接在“if”中使用返回码

if ping -w 10 -c2 adress &> /dev/null
then echo "Ok"
else echo "Call the sys admin"
fi

另请参阅 和 重定向的选项ping

相关内容