在小型移动设备(树莓派,手机、路由等)上自动化运行一个脚本,当设备接入到网络中且能够联系到指定服务器时,从服务器指定目录获取数据。常用于网络不稳定,或者位置不固定设备的数据同步。
参考代码如下:
#!/bin/sh
# 目标服务器的IP地址、用户名和密码
export SERVER_IP="172.16.22.33"
export USERNAME="root"
export PASSWORD="XXXXXXXXX"
export REMOTE_DIR="/home/senddata/"
export LOCAL_DIR="/home/getdata/"
echo " " > /home/getdata/log.txt
# 检测服务器是否存活并执行远程命令的函数
check_and_execute() {
# 使用ping命令检查服务器是否可达
if ping -c 1 $SERVER_IP &> /dev/null
then
echo "[ $(date) ] Server $SERVER_IP is up. Executing command..."
# 如果服务器在线,使用sshpass执行SSH命令
sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null $USERNAME@$SERVER_IP "yum install rsync -y"
if [ $? == 0 ];then
echo "server ip ${SERVER_IP}"
echo "starting transfer...."
echo "try runing.... : sshpass -p $PASSWORD rsync -avz -e 'ssh -o StrictHostKeyChecking=no' $USERNAME@$SERVER_IP:$REMOTE_DIR $LOCAL_DIR"
sshpass -p $PASSWORD rsync -avz -e "ssh -o StrictHostKeyChecking=no" $USERNAME@$SERVER_IP:$REMOTE_DIR $LOCAL_DIR
if [ $? == 0 ];then
sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null $USERNAME@$SERVER_IP "echo 'success!!' > ${REMOTE_DIR}FLAG.log "
echo "success!!!!!!!!!"
break
fi
else
echo "try login server failed!"
fi
else
echo "[ $(date) ]Server $SERVER_IP is down."
fi
}
# 每隔一分钟运行一次检测
while true
do
check_and_execute
sleep 1
done