2022年 11月 9日

Python实现运维案例

案例分析

概述 

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

Python基础环境准备

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

案例实现

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

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

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import os
  4. import shutil
  5. #
  6. # 处理文件及目录
  7. # @a_srcPath 目录路径
  8. # # copyOrMove 复制操作还是移动操作 False为复制操作,True为移动操作
  9. allfile = []
  10. def handle_dir(a_srcPath, a_findKey, a_copyOrMove=False):
  11. srcPathList = os.listdir(a_srcPath)
  12. #print(str(srcPathList))
  13. for sPath in srcPathList:
  14. filepath = os.path.join(a_srcPath, sPath)
  15. # print("filepath="+filepath)
  16. # 判断是目录
  17. if os.path.isdir(filepath):
  18. handle_dir(filepath, a_findKey, a_copyOrMove)
  19. if filepath.find(a_findKey)>=0:
  20. len_asrcPath = len(srcPath_root)
  21. destPath= destPath_root+filepath[len_asrcPath:]
  22. # destPath = filepath
  23. #print("destPath="+destPath)
  24. #print("filepath=" + filepath)
  25. allfile.append(destPath)
  26. if a_copyOrMove:
  27. shutil.move(filepath, destPath) #移动目录
  28. else:
  29. shutil.copytree(filepath, destPath) #复制目录
  30. return allfile
  31. findKey='2018-'
  32. srcPath_root='/home/mysoft/attachments'
  33. destPath_root='/home/mysoft/bk/attachments_history/'+findKey
  34. allfiles=handle_dir(srcPath_root,findKey,False)
  35. for item in allfiles:
  36. print(item)

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

 

持续完善,待续…