天天看点

Python实现运维案例案例分析案例实现

案例分析

概述 

          Python是一种跨平台编程语言,在多种平台都能得到很好的支持,在各种平台环境的运维过程中,有些工作是很繁琐重复的工作,可以编写脚本作为工具辅助运维工作,比如linux中使用shell脚本,但是shell脚本编写、调试比较困难,支持的辅助库少,编写稍微复杂些的功能就比较耗时、容易出错了。本文通过Python实现代码,作为学习和技术交流。

Python基础环境准备

参见:https://blog.csdn.net/yan_dk/article/details/89528463

案例实现

文件目录按关键词备份迁移

说明:工程目录中的附件有很多文件,积累了多年,导致整个应用目录非常庞大,历年记录基本上是不会读取的,只保留当年或当月的记录,这样太大不方便应用迁移,本例实现将附件文件的历史目录迁移备份到目标备份目录。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import  os
import shutil
#
# 处理文件及目录
# @a_srcPath 目录路径
# # copyOrMove 复制操作还是移动操作 False为复制操作,True为移动操作

allfile = []
def handle_dir(a_srcPath, a_findKey, a_copyOrMove=False):
    srcPathList = os.listdir(a_srcPath)
    #print(str(srcPathList))
    for sPath in srcPathList:
        filepath = os.path.join(a_srcPath, sPath)
        # print("filepath="+filepath)
        # 判断是目录
        if os.path.isdir(filepath):
          handle_dir(filepath, a_findKey, a_copyOrMove)
          if filepath.find(a_findKey)>=0:
             len_asrcPath = len(srcPath_root)
             destPath= destPath_root+filepath[len_asrcPath:]
             # destPath = filepath
             #print("destPath="+destPath)
             #print("filepath=" + filepath)
             allfile.append(destPath)
             if a_copyOrMove:  
                 shutil.move(filepath, destPath)    #移动目录
             else:
                 shutil.copytree(filepath, destPath) #复制目录

    return allfile

findKey='2018-'
srcPath_root='/home/mysoft/attachments'
destPath_root='/home/mysoft/bk/attachments_history/'+findKey

allfiles=handle_dir(srcPath_root,findKey,False)

for item in allfiles:
   print(item)
           

这样,就实现了复制、或者移动目录来迁移备份历史文件夹,而且按照指定关键词来建立文件夹,目录能得到比较完整的备份迁移,非常安全、方便。

持续完善,待续...

继续阅读