美文网首页
运维脚本常用

运维脚本常用

作者: 老夫刘某 | 来源:发表于2017-09-20 18:01 被阅读0次
  1. 标准输出显示文本名以及行号:

!/usr/bin/env python3

import fileinput

with fileinput.input('1.ttt') as f_input:
for line in f_input:
print(f_input.filename(),f_input.lineno(),line,end='')

  1. 替换文件内容并备份:

!/usr/bin/env python3

import fileinput

for line in fileinput.input('1.ttt',backup='.bak',inplace=1):
print(line.rstrip().replace('asd','Perl')) #将1.ttt文件中的asd替换成Perl

3.在指定文本的每一行的最前面加上‘=>’

!/usr/bin/env python3

import sys
import fileinput

for line in fileinput.input(r'/home/liujiangbu/hhhhhhh/1.ttt'):
sys.stdout.write('=> ')
sys.stdout.write(line)

  1. 将小写改成大写:

!/usr/bin/env python3

import fileinput
import glob

for line in fileinput.input(glob.glob("1.ttt")):
if fileinput.isfirstline():
print('-'20, 'Reading %s...' % fileinput.filename(), '-'20)
print(str(fileinput.lineno()) + ': ' + line.upper())

glob主要方法就是glob,该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径),比如:
import glob
glob.glob(r'c:/.txt')
我这里就是获得C盘下的所有txt文件
glob.glob(r'E:/pic/
/*.jpg')
获得指定目录下的所有jpg文件

  1. 利用fileinput及re做日志分析,提取所有含日期的行:
    import re
    import fileinput
    import sys

pattern = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'

for line in fileinput.input('error.log',backup='.bak',inplace=1):
if re.search(pattern,line):
sys.stdout.write("=> ")
sys.stdout.write(line)

---测试结果---

=> 1970-01-01 13:45:30 Error: **** Due to System Disk spacke not enough...
=> 1970-01-02 10:20:30 Error: **** Due to System Out of Memory...

=====================此处设计的re模块:
import re

将正则表达式编译成Pattern对象

pattern = re.compile(r'hello')

使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None

match = pattern.match('hello world!')

if match:
# 使用Match获得分组信息
print match.group()

输出

hello

re提供了众多模块方法用于完成正则表达式的功能。这些方法可以使用Pattern实例的相应方法替代,唯一的好处是少写一行re.compile()代码,但同时也无法复用编译后的Pattern对象。这些方法将在Pattern类的实例方法部分一起介绍。如上面这个例子可以简写为:

m = re.match(r'hello', 'hello world!')
print m.group()

  1. 利用fileinput根据argv命令行输入做替换:

---样本数据: host.txt

localhost is used to configure the loopback interface

when the system is booting. Do not change this entry.

127.0.0.1 localhost
192.168.100.2 www.test2.com
192.168.100.3 www.test3.com
192.168.100.4 www.test4.com

---测试脚本: test.py

import sys
import fileinput

source = sys.argv[1]
target = sys.argv[2]
files = sys.argv[3:]

for line in fileinput.input(files,backup='.bak',openhook=fileinput.hook_encoded("gb2312")):
#对打开的文件执行中文字符集编码
line = line.rstrip().replace(source,target)
print line

---输出结果:

c:>python test.py 192.168.100 127.0.0 host.txt

将host文件中,所有192.168.100转换为:127.0.0

127.0.0.1 localhost
127.0.0.2 www.test2.com
127.0.0.3 www.test3.com
127.0.0.4 www.test4.com

此处涉及到的rstrip方法:

返回值
返回删除 string 字符串末尾的指定字符后生成的新字符串。
实例
以下实例展示了rstrip()函数的使用方法:

!/usr/bin/python

str = " this is string example....wow!!! ";
print str.rstrip();
str = "88888888this is string example....wow!!!8888888";
print str.rstrip('8');
以上实例输出结果如下:
this is string example....wow!!!
88888888this is string example....wow!!!

  1. 读取配置文件:
    假如内容如下:

; config.ini
; Sample configuration file

[installation]
library=%(prefix)s/lib
include=%(prefix)s/include
bin=%(prefix)s/bin
prefix=/usr/local

Setting related to debug configuration

[debug]
log_errors=true
show_warnings=False

[server]
port: 8080
nworkers: 32
pid-file=/tmp/spam.pid
root=/www/root
signature:
=================================
Brought to you by the Python Cookbook
=================================

读取其中的值:

from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('config.ini')
['config.ini']
cfg.sections()
['installation', 'debug', 'server']
cfg.get('installation','library')
'/usr/local/lib'
cfg.getboolean('debug','log_errors')

True

修改配置使用 cfg.write() 方法将其写回到文件中:

cfg.set('server','port','9000')
cfg.set('debug','log_errors','False')
import sys
cfg.write(sys.stdout)

  1. 开启日志跟踪:
    import logging

def main():
# Configure the logging system
logging.basicConfig(
filename='app.log',
level=logging.ERROR #日志等级:critical,error,warning,info,debug
)

# Variables (to make the calls that follow work)
hostname = 'www.python.org'
item = 'spam'
filename = 'data.csv'
mode = 'r'

# Example logging calls (insert into your program)
logging.critical('Host %s unknown', hostname)
logging.error("Couldn't find %r", item)
logging.warning('Feature is deprecated')
logging.info('Opening file %r, mode=%r', filename, mode)
logging.debug('Got here')

if name == 'main':
main()
上面五个日志调用(critical(), error(), warning(), info(), debug())以降序方式表示不同的严重级别。 basicConfig() 的 level 参数是一个过滤器。 所有级别低于此级别的日志消息都会被忽略掉。 每个 logging 操作的参数是一个消息字符串,后面再跟一个或多个参数。 构造最终的日志消息的时候我们使用了%操作符来格式化消息字符串。

面的日志配置都是硬编码到程序中的。如果你想使用配置文件, 可以像下面这样修改 basicConfig() 调用:
import logging
import logging.config

def main():
# Configure the logging system
logging.config.fileConfig('logconfig.ini')
...

创建一个下面这样的文件,名字叫 logconfig.ini:
[loggers]
keys=root

[handlers]
keys=defaultHandler

[formatters]
keys=defaultFormatter

[logger_root]
level=INFO
handlers=defaultHandler
qualname=root

[handler_defaultHandler]
class=FileHandler
formatter=defaultFormatter
args=('app.log', 'a')

[formatter_defaultFormatter]
format=%(levelname)s:%(name)s:%(message)s

如果你想修改配置,可以直接编辑文件 logconfig.ini 即可。

相关文章

  • 运维脚本常用

    标准输出显示文本名以及行号: !/usr/bin/env python3 import fileinput wit...

  • 运维常用脚本

    Nginx日志日志割接及压缩 创建key用户登陆 用户名和密码一致,首次登陆会强制改密码(先输入当前密码,然后输入...

  • python 运维常用脚本

    Python 批量遍历目录文件,并修改访问时间 path="D:/UASM64/include/"dirs = o...

  • 五个python常用运维脚本面试题实例

    五个python常用运维脚本面试题实例 来源:马哥教育 原文作者:chengxuyuan 链接:https://m...

  • 2018-11-23

    Linux运维常用脚本 一、根据PID过滤进程所有信息 ! /bin/bashread -p "请输入要查询的PI...

  • linux: 常用shell脚本珍藏

    我们在运维中,尤其是linux运维,都知道脚本的重要性,脚本会让我们的 运维事半功倍,所以学会写脚本是我们每个li...

  • oracle 运维常用脚本(参数篇)

    当你初为DBA角色,以下脚本能助力一臂之力,已经进化D请飘过. 调整 db_files 数量默认为200,调整更大...

  • oracle 运维常用脚本(函数篇)

    创建表空间 表空间容量视图 自动追加数据文件(表空间自动维护集群版) httpPost 与外部交互(需开ACL网络...

  • oracle 运维常用脚本(SQL篇)

    锁表处理 追加数据文件到表空间 ASM磁盘组空间查询 删除表空间文件 正在执行的sql语句及执行该语句的用户 正在...

  • Oracle 日常运维常用SQL脚本

    正在执行的语句查询和拼接杀进程 锁表语句杀进程 最耗费CPU 最耗费CPU的sql语句 数据库状态分析 最耗缓存 ...

网友评论

      本文标题:运维脚本常用

      本文链接:https://www.haomeiwen.com/subject/xdwosxtx.html