rsync自动输入密码实现数据备份

Vimer 2010-07-15 08:46:24 累计浏览 5,322 次

最近有点背,在64位suse上大家django环境出了一堆问题,最后服务器还不稳定不能用……
由于做不了webserver,所以只能用来做备份服务器了,需求比较简单,就是将源服务器的一个目录每天copy过来做备份。其实就是用rsync或者scp即可,最后的问题就变成了怎么让rsync自动输入服务器密码,结果在网上搜了一下方法,有rsyncserver,公秘钥,之类,杯具的是我配置了一下午也没搞定……

然后想起公司有同事之前做过一个自动登录服务器的脚本,是不是只要改一下执行的命令即可呢?修改后的代码如下:

#!/usr/bin/expect -f
#auto ssh login
proc wait {} {
  expect {
    "*asswor*" {
      send
not!@#rated\n
      expect {
        "*asswor*" {
          puts stderr "Unknown password."
          exit 1
        }
        "$*" { }
        ">*" { }
        "#*" { }
      }
    }
    "$*" { }
    ">*" { }
    "#*" { }
  }
}
if {[llength $argv] < 1} {
  puts "Usage: [exec basename $argv0] Host."
  exit 1
}
set timeout 30
set dir [lindex $argv 0]
set passwd "dantezhu"
#exp_internal 1
spawn mkdir -p /data/mman_backup/$dir
spawn [exec which rsync] dantezhu@10.6.207.84#36000:/home/dantezhu/release/dgwww/upload /data/mman_backup/$dir -ar --progress
expect {
  "*asswor*" {
    send "dantezhu\n"
    wait 
  }
  "*no)?*" {
    send "yes\n";
    expect {
      "*assword*" {
        send "$passwd\n"
        wait 
       }
    }
  }
  timeout {
    puts "Timeout!"
    exit 1
  }
}
interact

由于是在不知道怎么在这个脚本里面获取当前的年月日,所以又在外面写了一层python(表BS我……)

#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import os
timeHere = time.strftime('%m/%d',time.localtime())
cmd = '/home/dantezhu/py_backup/backup_data '+ timeHere
os.system(cmd)

测了一下,一切正常,然后在crontab中加入定时脚本,让它每天0点半执行:

30 0 * * *                      python /home/dantezhu/py_backup/rsync_backup.py >> /data/mman_backup/backup.log 2>&1 &

附:代码下载

同分类推荐文章

  1. NGINX Gateway Fabric 2.8: IP allow and deny lists, passive health checks, and cookie-based session persistence (2026-11-14 01:10:02)
  2. NGINX Ingress Controller 5.7: HTTP/2 to your upstreams, Opaque Secrets, and cert-manager challenges behind HTTPS redirects (2026-11-14 00:10:02)
  3. Hexo 文章一键发布到微信公众号 (2026-11-13 19:10:02)

查看更多 DevOps 文章 →

建议继续学习

  1. WEB系统需要关注的一些点 (累计阅读 19,283)
  2. 批量添加主机到cacti+nagios的监控报警系统中 (累计阅读 15,537)
  3. 高效Linux用户需要了解的命令行技能 (累计阅读 13,237)
  4. Linux命令行里的“瑞士军刀” (累计阅读 11,983)
  5. linux 建立两台机器的信任关系 (累计阅读 11,821)
  6. rsync同步的艺术 (累计阅读 10,208)
  7. 应该知道的Linux技巧 (累计阅读 9,340)
  8. sshd+chrome+switchsharp翻墙 (累计阅读 9,036)
  9. 你可能不知道的Shell (累计阅读 8,762)
  10. Linux shell脚本使用while循环执行ssh的注意事项 (累计阅读 8,492)