python学习之运维应用

########运维应用#########
1.文件操作
In [1]: import os

In [2]: import shutil

In [3]: with open('file1','a+') as f:
   ...:     f.write('this is a file')
   ...:     

In [6]: 'file1' in os.listdir('.')
Out[6]: True
• shutil模块简单来说是用来复制、归档文件和目录
• shutil.copyfile(src,dst) 复制一个文件,只能复制文件到文件,不能复制文件到目录
In [7]: shutil.copyfile('file1','file2')        ##复制文件

In [8]: 'file2' in os.listdir('.')
Out[8]: True
• shutil.copymod(src,dst)     复制文件权限 , 将文件权限同步到其他文件
• shutil.copy(src,dst)         源必须是文件,但是 dst 可以是文件或者目录,与cp 类似
In [9]: shutil.copy('file1','/root/Desktop/ipython/')

In [10]: 'file1' in os.listdir('/root/Desktop/ipython/')
Out[10]: True
• shutil.copy2(src,dst)     与 copy 类似,但是源数据也会复制,类似cp -p 命令,将权限,时间戳等源数据也复制过去。
• shutil.copytree(src,dst)     以copy2 的方式递归复制一个目录
In [12]: shutil.copytree('redhat/','/root/Desktop/ipython/redhat0')
• shutil.rmtree(path)         递归删除一个目录
In [18]: os.removedirs('/root/Desktop/ipython/redhat0/')
2.shutil 模块
• 打包压缩:
shutil.make_archive(base_name, format, root_dir=None,base_dir=None)
•basename: 打包后的文件名称,
•format: 以什么样的格式打包, rootdir 压缩的根目录。
•base_dir 开始压缩的目录。
•rootdir 和 basedir 默认都是当前目录
• 查看都支持哪些打包格式:
shutil.get_archive_formats()
In [19]: shutil.get_archive_formats()
Out[19]:
[('bztar', "bzip2'ed tar-file"),
 ('gztar', "gzip'ed tar-file"),
 ('tar', 'uncompressed tar file'),
 ('zip', 'ZIP file')]

3.进程管理
•psutil 是一个第三方模块,需要单独安装 : easy_install psutil
•/proc 目录中的主要文件的说明只简单列出几个经常用到监控中的文件
•/proc/cpuinfo CPU 信息
•/proc/loadavg 系统平均负载信息
•/proc/meminfo 内存相关信息,包括物理内存和交换分区
•/proc/swaps 交换分区使用情况
•案例
• 读取负载信息
• 监控 mariadb 进程是否存在
• 备份/home目录,备份的包名称为homeback_YY_MM_DD.tar.gz
import shutil
import time
shutil.make_archive('homeback%s'%(time.strftime('%Y_%m_%d')),'gztar','/home')
print 'homeback%s'%(time.strftime('%Y_%m_%d'))
print time.strftime('%Y_%m_%d')
输出为:
homeback2017_07_16
2017_07_16



4.处理ip地址

In [4]: from IPy import IP

In [5]: IP('172.25.254.0/24')
Out[5]: IP('172.25.254.0/24')

In [6]: IP('172.25.254.0/24').len()
Out[6]: 256

In [7]: IP('172.25.254.0/24').net()
Out[7]: IP('172.25.254.0')

In [8]: IP('172.25.254.0/24').netmask()
Out[8]: IP('255.255.255.0')

In [9]: IP('172.25.254.0/24').iptype()
Out[9]: 'PRIVATE'

In [10]: IP('172.25.254.0/24').version()
Out[10]: 4

In [11]: ip = IP('172.25.254.0/24')

In [12]: for x in ip:
   ....:     print (x)
   ....:     
172.25.254.0
172.25.254.1
172.25.254.2
172.25.254.3
172.25.254.4
172.25.254.5
172.25.254.6
172.25.254.7
172.25.254.8
In [14]: IP('127.0.0.0/30').version()
Out[14]: 4

In [15]: IP('::1').version()
Out[15]: 6










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值