Linux 刪除日誌寫指令碼思路
需求
刪除指定目錄下的日誌檔案,有且只刪除30天及以前的日誌檔案,30天內的日誌檔案予以保留
有多臺Lunux
伺服器均要執行此任務
拆分技術點
刪除執行時間範圍的日誌
查詢關鍵詞:linux delete files older than
找到資料:How to Delete Files Older than 30 days in Linux
稍作修改,得到命令
find folderName -type f -mtime +30 -delete
迴圈資料夾執行此操作
查詢關鍵詞:linux loop command
找到資料:How to make a for loop in command line?
得到命令:
for dir in yourSumFolder/*; do (find "$dir" -type f -mtime +30 -delete); done
這裡的yourSumFolder
是上面的命令folderName
的父級目錄,這句話的意思是,迴圈yourSumFolder下面的所有子目錄,執行find "$dir" -type f -mtime +30 -delete
操作
遠端訪問伺服器
查詢關鍵詞:linux remote login with password
然後找到了一個新的關鍵詞sshpass
然後查詢關鍵詞:sshpass
檢視資料sshpass: An Excellent Tool for Non-Interactive SSH Login – Never Use on Production Server
得到以下命令:
sshpass -p "password" ssh -p portIfNot22 -o StrictHostKeyChecking=no YourAccount@YourIP
遠端訪問並執行多個命令
根據迴圈刪除檔案的指令,我們需要先cd
到yourSumFolder資料夾,然後才能順利執行指令碼,所以會執行多個命令
查詢關鍵詞:linux sshpass execute command
找到資料:Execute Commands on Remote Machines using sshpass,How To Run Multiple SSH Command On Remote Machine And Exit Safely
以上兩篇資料說使用英文分號
;
或者&&
分隔命令都可以,博主最後採用的是&&
寫出以下命令:
sshpass -p "password" ssh -p portIfNot22 -o StrictHostKeyChecking=no YourAccount@YourIP "cd yourSumSumFolder && for dir in yourSumFolder/*; do (find "$dir" -type f -mtime +30 -delete); done"
解決報錯
嘗試執行上述命令,報錯:
Pseudo-terminal will not be allocated because stdin is not a terminal.
直接查詢錯誤內容,得到結果:ssh登入問題出現Pseudo-terminal will not be allocated because stdin is not a terminal錯誤
在命令上加上-tt
sshpass -p "password" ssh -p portIfNot22 -o StrictHostKeyChecking=no YourAccount@YourIP -tt "cd yourSumSumFolder && for dir in yourSumFolder/*; do (find "$dir" -type f -mtime +30 -delete); done"
整合多個伺服器的業務指令碼
echo "正在刪除伺服器A日誌..."
sshpass -p "password" ssh -p portIfNot22 -o StrictHostKeyChecking=no YourAccount@YourIP -tt "cd yourSumSumFolder && for dir in yourSumFolder/*; do (find "$dir" -type f -mtime +30 -delete); done"
echo "刪除伺服器A完成"
echo "正在刪除伺服器B日誌..."
sshpass -p "password" ssh -p portIfNot22 -o StrictHostKeyChecking=no YourAccount@YourIP -tt "cd yourSumSumFolder && for dir in yourSumFolder/*; do (find "$dir" -type f -mtime +30 -delete); done"
echo "刪除伺服器B完成"
執行
查詢關鍵詞:Linux run sh
得到資料:How To Run the .sh File Shell Script In Linux / UNIX
將寫好的sh指令碼上傳伺服器,在sh指令碼對應目錄下執行:
sh xxx.sh
思路延展
可以寫出定時執行這個sh檔案,達到定時刪除的目的
自己想一下怎麼查,關鍵詞應該是什麼