我被一个奇怪的问题困扰着,当通过 crontab 执行 rsync 命令时,它没有运行。
以下是代码:
#!/bin/sh -x
PATH=/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/mysql/bin:/opt/android-sdk-linux/tools:/opt/android-sdk-linux/platform-tools:~/usr/lib/jvm/jdk-6/bin
/bin/sh /etc/profile
MyUSER="root" # USERNAME
MyPASS="password" # PASSWORD
MyHOST="localhost" # Hostname
Password="" #Linux Password
MYSQL="$(which mysql)"
if [ -z "$MYSQL" ]; then
echo "Error: MYSQL not found"
exit 1
fi
MYSQLADMIN="$(which mysqladmin)"
if [ -z "$MYSQLADMIN" ]; then
echo "Error: MYSQLADMIN not found"
exit 1
fi
CHOWN="$(which chown)"
if [ -z "$CHOWN" ]; then
echo "Error: CHOWN not found"
exit 1
fi
CHMOD="$(which chmod)"
if [ -z "$CHMOD" ]; then
echo "Error: CHMOD not found"
exit 1
fi
GZIP="$(which gzip)"
if [ -z "$GZIP" ]; then
echo "Error: GZIP not found"
exit 1
fi
CP="$(which cp)"
if [ -z "$CP" ]; then
echo "Error: CP not found"
exit 1
fi
MV="$(which mv)"
if [ -z "$MV" ]; then
echo "Error: MV not found"
exit 1
fi
RM="$(which rm)"
if [ -z "$RM" ]; then
echo "Error: RM not found"
exit 1
fi
RSYNC="$(which rsync)"
if [ -z "$RSYNC" ]; then
echo "Error: RSYNC not found"
exit 1
fi
MYSQLBINLOG="$(which mysqlbinlog)"
if [ -z "$MYSQLBINLOG" ]; then
echo "Error: MYSQLBINLOG not found"
exit 1
fi
# Get data in dd-mm-yyyy format
NOW="$(date +"%d-%m-%Y-%T")"
DEST="/home/db-backup"
mkdir $DEST/Increment_backup.$NOW
LATEST=$DEST/Increment_backup.$NOW
$MYSQLADMIN -u$MyUSER -p$MyPASS flush-logs
newestlog=`ls -d /usr/local/mysql/data/mysql-bin.?????? | sed 's/^.*\.//' | sort -g | tail -n 1`
echo $newestlog
for file in `ls /usr/local/mysql/data/mysql-bin.??????`
do
if [ "/usr/local/mysql/data/mysql-bin.$newestlog" != "$file" ]; then
echo $file
echo $Password | sudo -S $CHMOD 0777 $file
#sudo $MYSQLBINLOG $file>$file.$NOW.sql
$CP "$file" $LATEST
#$RM "$file.$NOW.sql"
#$MV $file.sql.gz /$LATEST
fi
done
for file1 in `ls $LATEST/mysql-bin.??????`
do
$MYSQLBINLOG $file1>$file1.$NOW.sql
$GZIP -9 "$file1.$NOW.sql"
$RM "$file1"
done
$RSYNC -v -e ssh $LATEST [email protected]:/home/rsync-backup/
#FILE=$LATEST/"mysql-bin.??????"
#$MYSQLBINLOG $FILE>$FILE.$NOW.sql
#$GZIP -f "$FILE.$NOW.sql"
pwd
手动运行代码时,Rsync 会发生,但通过 crontab 运行时会失败。其余命令运行正常。从日志中我得到了以下信息:
Host key verification failed.^M
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(600) [sender=3.0.6]
答案1
ssh
(rsync
执行)不信任服务器的主机密钥,而且由于没有交互式终端提示用户,因此它只会失败。原因可能是在 cron 下运行时查看的文件与手动执行时ssh
查看的文件不同。known_hosts
如果 cronjob 以不同的用户身份运行,则需要通过执行以下操作手动接受主机密钥:
sudo -u cronuser HOME=/home/cronuser ssh [email protected]
如果 cronjob 以您的用户身份运行,则$HOME
可能设置不正确。在 crontab 中明确指定:
HOME=/home/vishu
答案2
谢谢大家……终于找到答案了。当我手动运行它时,我是以本地用户身份运行的。但是,在 cron 上,我是以 root 用户身份运行它的,因此没有为其生成 ssh 密钥。我创建了ssh-keygen
密钥。现在它可以正常工作了。
答案3
我遇到了类似的错误。这解决了我的问题:使用 rsync 迁移数据的主机通过 ssh 连接。之后,主机 IP 被永久添加到已知主机列表中。
接下来我运行了相同的 rsync 命令,它执行得很好!