自动备份远程文件到本地


  1. 自动登录远程机器,自动输入密码和yes/no等,可以利用expect,需要先安装。

  2. 自动备份远程机器上的文件(remote_bak.sh):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #! /usr/bin/expect
    set timeout 3600
    set password yourpassword
    spawn scp -r remote_host:/path/to/files /local/path/to/remote_baks/
    expect {
    "(yes/no)?" {
    send "yes\n"
    expect "*assword:" { send "$password\n"}
    }
    "*assword:" {
    send "$password\n"
    }
    }
    expect "100%"
    expect eof
  3. 自动备份远程机器数据库到本地:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    #/usr/bin/bash
    CMD_PROMPT=".+@.+:.+#"
    user=root
    host=hw
    password=pwd
    database=db
    expect <<EOF
    set timeout 3600
    spawn ssh $user@$host
    expect {
    "yes/no" { send "yes\n";exp_continue }
    "*password:" { send "$password\n" }
    }
    expect -re $CMD_PROMPT { send "sudo mysqldump ${database} > ${database}_temp.sql\n" }
    expect -re $CMD_PROMPT { send "exit\n" }
    expect eof
    EOF
    mkdir mysqlbak
    expect <<EOF
    spawn scp $user@$host:~/${database}_temp.sql mysqlbak/
    expect {
    "yes/no" { send "yes\n";exp_continue }
    "*password:" { send "$password\n" }
    }
    expect eof
    EOF
  4. 创建crontab

    1
    2
    3
    #早上5点执行脚本
    crontab -e
    0 5 * * * /absolute/path/to/remote_bak.sh > /dev/null 2>&1 &

大功告成!