专栏名称: 马哥Linux运维
马哥linux致力于linux运维培训,连续多年排名第一,订阅者可免费获得学习机会和相关Linux独家实战资料!
目录
相关文章推荐
运维  ·  再见,CDN 巨头:Akamai 宣布 ... ·  2 天前  
51好读  ›  专栏  ›  马哥Linux运维

经典!Python运维中常用的几十个Python运维脚本

马哥Linux运维  · 公众号  · 运维  · 2018-10-18 22:09

正文

file是一个类,使用file('file_name', 'r+')这种方式打开文件,返回一个file对象,以写模式打开文件不存在则会被创建。但是更推荐使用内置函数open()来打开一个文件。



首先 open是内置函数 ,使用方式是open('file_name', mode, buffering),返回值也是一个file对象,同样,以写模式打开文件如果不存在也会被创建一个新的。

f=open('/tmp/hello','w')

#open(路径+文件名,读写模式)

#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式

如:'rb','wb','r+b'等等

读写模式的类型有:

rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)

w     以写方式打开,

a     以追加模式打开 (从 EOF 开始, 必要时创建新文件)

r+     以读写模式打开

w+     以读写模式打开 (参见 w )

a+     以读写模式打开 (参见 a )

rb     以二进制读模式打开

wb     以二进制写模式打开 (参见 w )

ab     以二进制追加模式打开 (参见 a )

rb+    以二进制读写模式打开 (参见 r+ )

wb+    以二进制读写模式打开 (参见 w+ )

ab+    以二进制读写模式打开 (参见 a+ )

注意:

1、使用'W',文件若存在,首先要清空,然后(重新)创建,

2、使用'a'模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。

f.read([size]) size未指定则返回整个文件,如果文件大小>2倍内存则有问题.f.read()读到文件尾时返回""(空字串)

file.readline() 返回一行

file.readline([size]) 返回包含size行的列表,size 未指定则返回全部行

for line in f:

print line #通过迭代器访问

f.write("hello\n") #如果要写入字符串以外的数据,先将他转换为字符串.

f.tell() 返回一个整数,表示当前文件指针的位置(就是到文件头的比特数).

f.seek(偏移量,[起始位置])

用来移动文件指针

偏移量:单位:比特,可正可负

起始位置:0-文件头,默认值;1-当前位置;2-文件尾

f.close() 关闭文件

要进行读文件操作,只需要把模式换成'r'就可以,也可以把模式为空不写参数,也是读的意思,因为程序默认是为'r'的。

>>>f = open('a.txt', 'r')

>>>f.read(5)

'hello'

read( )是读文件的方法,括号内填入要读取的字符数,这里填写的字符数是5,如果填写的是1那么输出的就应该是‘h’。

打开文件文件读取还有一些常用到的技巧方法,像下边这两种:

1 、read( ):表示读取全部内容

2、readline( ):表示逐行读取


一、用Python写一个列举当前目录以及所有子目录下的文件,并打印出绝对路径



#!/ magedu/bin /env python

import os

for root,dirs,files in os.walk('/tmp'):

for name in files:

print (os.path.join(root,name))

os.walk()

原型为:os.walk(top, topdown=True, onerror=None, followlinks=False)


我们一般只使用第一个参数。(topdown指明遍历的顺序)


该方法对于每个目录返回一个三元组,(dirpath, dirnames, filenames)。

第一个是路径,第二个是路径下面的目录,第三个是路径下面的非目录(对于windows来说也就是文件)

os.listdir(path)

其参数含义如下。path 要获得内容目录的路径



二、写程序打印三角形



#!/ magedu/bin/ env python

input = int(raw_input('input number:'))

for i in range(input):

for j in range(i):

print '*',

print '\n'



三、猜数器,程序随机生成一个个位数字,然后等待用户输入,输入数字和生成数字相同则视为成功。



成功则打印三角形。失败则重新输入(提示:随机数函数:random)


#!/ magedu/bin /env python

import random

while True:

input = int(raw_input('input number:'))

random_num = random.randint(1, 10)

print input,random_num

if input == random_num:

for i in range(input):

for j in range(i):

print '*',

print '\n'

else:

print 'please input number again'


四、请按照这样的日期格式(xxxx-xx-xx)每日生成一个文件,例如今天生成的文件为2016-09-23.log, 并且把磁盘的使用情况写到到这个文件中。


#!/magedu/bin/env python

#!coding=utf-8

import time

import os

new_time = time.strftime('%Y-%m-%d')


disk_status = os.popen('df -h').readlines()


str1 = ''.join(disk_status)


f = file(new_time+'.log','w')


f.write('%s' % str1)

f.flush()

f.close()


五、统计出每个IP的访问量有多少?(从日志文件中查找)


#!/ magedu/bin /env python

#!coding=utf-8

list = []

f = file('/tmp/1.log')

str1 = f.readlines()

f.close()

for i in str1:

ip =  i.split()[0]


list.append(ip)


list_num = set(list)


for j in list_num:

num = list.count(j)

print '%s : %s' %(j,num)


1. 写个程序,接受用户输入数字,并进行校验,非数字给出错误提示,然后重新等待用户输入。

2. 根据用户输入数字,输出从0到该数字之间所有的素数。(只能被1和自身整除的数为素数)

#!/ magedu/bin /env python

#coding=utf-8

import tab

import sys

while True:

try:

n = int(raw_input('请输入数字:').strip())

for i in range(2, n + 1):

for x in range(2, i):

if i % x == 0:

break

else:

print i

except ValueError:

print('你输入的不是数字,请重新输入:')

except KeyboardInterrupt:

sys.exit('\n')


六、python练习 抓取web页面



from urllib import urlretrieve

def firstNonBlank(lines):

for e achLine in lines:

if not eachLine.strip():

continue

else:

return eachLine

def firstLast(webpage):

f=open(webpage)

lines=f.readlines()

f.close

print firstNonBlank(lines), #调用函数

lines.reverse()

print firstNonBlank(lines),

def download(url= 'http://www.magedu.com/72446.html',process=firstLast):

try:

retval = urlretrieve(url) [0]

except IOError:

retval = None

if retval:

process(retval)

if __name__ == '__main__':

download()


七、Python中的sys.argv[]用法练习


#!/ magedu/bin /python

# -*- coding:utf-8 -*-

import sys

def readFile(filename):

f = file(filename)

while True:

fileContext = f.readline()

if len(fileContext) ==0:

break;

print fileContext

f.close()

if len(sys.argv) < 2:

print "No function be setted."

sys.exit()


if sys.argv[1].startswith("-"):


option = sys.argv[1][1:]


if option == 'version':

print "Version1.2"

elif option == 'help':

print "enter an filename to see the context of it!"

else:

print "Unknown function!"

sys.exit()

else:

for filename in sys.argv[1:]:

readFile(filename)



八、python迭代查找目录下文件


#两种方法

#!/ magedu/bin /env python

import os

dir='/root/sh'

'''

def fr(dir):

filelist= os.listdir (dir)

for i in filelist:

fullfile= os.path.join (dir,i)

if not os.path.isdir (fullfile):

if i == "1.txt":

#print fullfile

os.remove (fullfile)

else:

fr(fullfile)

'''

'''

def fw()dir:

for root,dirs,files in os.walk(dir):

for f in files:

if f == "1.txt":

#os.remove(os.path.join(root,f))

print os.path.join(root,f)

'''


九、ps 可以查看进程的内存占用大小,写一个脚本计算一下所有进程所占用内存大小的和。



(提示,使用ps aux 列出所有进程,过滤出RSS那列,然后求和)


#!/ magedu/bin /env python

#!coding=utf-8

import os

list = []

sum = 0

str1 = os.popen('ps aux','r').readlines()

for i in str1:

str2 = i.split()

new_rss = str2[5]

list.append (new_rss)

for i in  list[1:-1]:

num = int(i)

sum = sum + num

print '%s:%s' %(list[0],sum)


写一个脚本,判断本机的80端口是否开启着,如果开启着什么都不做,如果发现端口不存在,那么重启一下httpd服务,并发邮件通知你自己。脚本写好后,可以每一分钟执行一次,也可以写一个死循环的脚本,30s检测一次。


#!/ magedu/bin /env python

#!coding=utf-8

import os

import time

import sys

import smtplib

from email.mime.text import MIMEText

from email.MIMEMultipart import MIMEMultipart


def sendsimplemail (warning):

msg = MIMEText (warning)

msg['Subject'] = 'python first mail'

msg['From'] = 'root@localhost'

try:

smtp = smtplib.SMTP ()

smtp.connect (r'smtp.126.com')

smtp.login('要发送的邮箱名', '密码')

smtp.sendmail ('要发送的邮箱名', ['要发送的邮箱名'], msg.as_string())

smtp.close()

except Exception, e:

print e


while True:

http_status = os.popen('netstat -tulnp | grep httpd','r').readlines()

try:

if http_status == []:

os.system('service httpd start')

new_http_status = os.popen('netstat -tulnp | grep httpd','r').readlines()

str1 = ''.join(new_http_status)

is_80 = str1.split()[3].split(':')[-1]

if is_80 != '80':

print 'httpd 启动失败'

else:

print 'httpd 启动成功'

sendsimplemail(warning = "This is a warning!!!")#调用函数

else:

print 'httpd正常'

time.sleep(5)

except KeyboardInterrupt:

sys.exit('\n')


#!/ magedu/bin /python

#-*- coding:utf-8 -*-

#输入这一条就可以在Python脚本里面使用汉语注释!此脚本可以直接复制使用;

while True:            #进入死循环

input = raw_input('Please input your username:')

#交互式输入用户信息,输入input信息;

if input == "wenlong":

#如果input等于wenlong则进入此循环(如果用户输入wenlong)

password = raw_input('Please input your pass:')

#交互式信息输入,输入password信息;

p = '123'

#设置变量P赋值为123

while password != p:

#如果输入的password 不等于p(123), 则进此入循环

password = raw_input('Please input your pass again:')

#交互式信息输入,输入password信息;

if password == p:

#如果password等于p(123),则进入此循环

print 'welcome to select system!'              #输出提示信息;

while True:

#进入循环;

match = 0

#设置变量match等于0;

input = raw_input("Please input the name whom you want to search :")

#交互式信息输入,输入input信息;

while not input.strip():

#判断input值是否为空,如果input输出为空,则进入循环;

input = raw_input("Please input the name whom you want to search :")

#交互式信息输入,输入input信息;

name_file = file('search_name.txt')

#设置变量name_file,file('search_name.txt')是调用名为search_name.txt的文档

while True:

#进入循环;

line = name_file.readline()           #以行的形式,读取search_name.txt文档信息;

if len(line) == 0:      #当len(name_file.readline() )为0时,表示读完了文件,len(name_file.readline() )为每一行的字符长度,空行的内容为\n也是有两个字符。len为0时进入循环;

break       #执行到这里跳出循环;

if input in line:    #如果输入的input信息可以匹配到文件的某一行,进入循环;

print 'Match item: %s'  %line     #输出匹配到的行信息;

match = 1    #给变量match赋值为1

if match == 0 :              #如果match等于0,则进入   ;

print 'No match item found!'         #输出提示信息;

else: print "Sorry ,user  %s not found " %input      #如果输入的用户不是wenlong,则输出信息没有这个用户;




#!/ magedu/bin /python

while True:

input = raw_input('Please input your username:')

if input == "wenlong":

password = raw_input('Please input your pass:')

p = '123'

while password != p:

password = raw_input('Please input your pass again:')

if password == p:

print 'welcome to select system!'

while True:

match = 0

input = raw_input("Please input the name whom you want to search :")

while not input.strip():

print 'No match item found!'

input = raw_input("Please input the name whom you want to search :")

name_file = file('search_name.txt')

while True:

line = name_file.readline()

if len(line) == 0:

break

if input in line:







请到「今天看啥」查看全文