请提高这段代码的鲁棒性并增加自检能力:filepath=/home/yumi/camcap/ echo "`date +%Y%m%d` start upload......" echo "`date +%Y%m%d` start upload......" > /home/yumi/camcap/log/import.log sleep 5 password='sjmSJM11870' echo "start copy datafile from remote path..." echo "start copy datafile from remote path..." >> /home/yumi/camcap/log/import.log /usr/bin/expect <<EOF set timeout 10 spawn scp -r -p $filepath ubuntu@43.143.22.12:/home/ubuntu/camcapdata/ expect { "(yes/no)?" { send "yes\n" expect "*assword:" {send "$password\n"} } "*assword:" { send "$password\n" } } send "exit\n" expect eof EOF if [ $? = 0 ]; then echo "datafile copy successful!" echo "datafile copy successful!" >> /home/import.log else echo "datafile copy failed!" echo "datafile copy failed!" >> /home/import.log fi
时间: 2023-06-16 11:04:11 浏览: 171
针对这段代码,我们可以进行如下的鲁棒性和自检改进:
1. 鲁棒性改进:
- 在进行 scp 操作前,可以先检查要上传的文件或目录是否存在,如果不存在,则可以给出相应的提示信息。
- 在进行 scp 操作时,可以增加对远程主机的连通性检查。如果远程主机不可达,则可以给出相应的提示信息。
- 在进行 scp 操作时,可以增加对本地和远程主机的文件系统容量进行检查。如果空间不足,则可以给出相应的提示信息。
2. 自检改进:
- 在进行 scp 操作后,可以检查目标文件或目录是否被成功复制。如果复制失败,则可以给出相应的提示信息。
- 在进行 scp 操作时,可以记录日志文件,以便后续查看操作结果。
改进后的代码如下:
```
#!/bin/bash
filepath=/home/yumi/camcap/
logfile=/home/yumi/camcap/log/import.log
remotepath=/home/ubuntu/camcapdata/
remoteserver=ubuntu@43.143.22.12
password='sjmSJM11870'
echo "$(date +%Y%m%d) start upload......"
echo "$(date +%Y%m%d) start upload......" > $logfile
# check local file/directory existence
if [ ! -e "$filepath" ]; then
echo "Local file/directory $filepath does not exist."
echo "Local file/directory $filepath does not exist." >> $logfile
exit 1
fi
# check remote server accessibility
if ! ping -c 1 $remoteserver >/dev/null 2>&1; then
echo "Remote server $remoteserver is not reachable."
echo "Remote server $remoteserver is not reachable." >> $logfile
exit 1
fi
# check remote server file system capacity
if ! ssh $remoteserver "df -h $remotepath" >/dev/null 2>&1; then
echo "Remote server file system does not have enough space."
echo "Remote server file system does not have enough space." >> $logfile
exit 1
fi
echo "Start copying datafile from $filepath to $remoteserver:$remotepath..."
echo "Start copying datafile from $filepath to $remoteserver:$remotepath..." >> $logfile
# start scp operation
/usr/bin/expect <<EOF
set timeout 10
spawn scp -r -p $filepath $remoteserver:$remotepath
expect {
"(yes/no)?" {
send "yes\n"
expect "*assword:" {send "$password\n"}
}
"*assword:" {
send "$password\n"
}
}
send "exit\n"
expect eof
EOF
# check scp operation result
if [ $? -eq 0 ]; then
echo "Datafile copy successful!"
echo "Datafile copy successful!" >> $logfile
else
echo "Datafile copy failed!"
echo "Datafile copy failed!" >> $logfile
fi
```
阅读全文