Exploring and Thinking

Linux備份檔案至Nas

這個範例是將Linux系統內的檔案,備份至Nas系統。

採取的方式是每天固定時間抓取Linux檔案,使用copy方式至Nas。

bash檔特殊的地方,主要是第五行和第六行,分別取得當天的日期和星期,格式單純數字化(大Y指四位數年份)。

因Linux每天將產生的檔案,分別放在0~6的資料夾內,代表星期日~星期六。因此我做一個迴圈判斷式,若今天是星期一,bkDateW=1,則會抓取資料夾"1"內的檔案。

抓到資料後,將檔案複製到Nas,檔名前面加日期"$bkDate"。
 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
27
28
29
30
31
32
33
34
35
36
37
38
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
 
bkDate=$(date --d="today" +%Y%m%d) # Get the date of today, format: 20120316
bkDateW=$(date --d="today" +%w) # Get the date of week, format: 5
 
# Copy and rename files to Nas.
case $bkDateW in
 
        "0")
        cp file/0/testFile bkEMtemp/"$bkDate"_testFile
        ;;
 
        "1")
        cp file/1/testFile bkEMtemp/"$bkDate"_testFile
        ;;
 
        "2")
        cp file/2/testFile bkEMtemp/"$bkDate"_testFile
        ;;
 
        "3")
        cp file/3/testFile bkEMtemp/"$bkDate"_testFile
        ;;
 
        "4")
        cp file/4/testFile bkEMtemp/"$bkDate"_testFile
        ;;
 
        "5")
        cp file/5/testFile bkEMtemp/"$bkDate"_testFile
        ;;
 
        "6")
        cp file/6/testFile bkEMtemp/"$bkDate"_testFile
        ;;
esac

接著我用root去vi rc.local(一般位在/etc/rc.local, 找不到可使用 find / -name rc.local 指令尋找),mount 資料夾 bkEMtemp。在此之前需先建一個資料夾,如本例的bkEMtemp,再chmod 777 (設定權限)。

這樣每次重開機進來時,系統就會將nas資料夾mount進來。

1
mount -t cifs //nas的ip/資料夾 /home/帳號/bkEMtemp -o user=account,pass=password

最後在原本的帳號,輸入「crontab -e」,將排程放進去,此例是每天下午四點半執行bkEM.sh。

bkEM.sh也需設定權限,chmod 755才行喔!
1
30 16 * * * /home/帳號/bkEM.sh

Share:

熱門文章

標籤