前言

  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写一个列举当前目录以及所有子目录下的文件,并打印出绝对路径

#!/usr/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 要获得内容目录的路径

二、写程序打印三角形

#!/usr/bin/env python

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

for i in range(input):

for j in range(i):

print '*',

print '\n'

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

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

#!/usr/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, 并且把磁盘的使用情况写到到这个文件中。


#!/usr/bin/env python

#!coding=utf-8

import time

import os

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

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

st1 = ''.join(disk_status)

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

f.write('%s' % str1)

f.flush()

f.close()

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


#!/usr/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. 写个程序,接受用户输入数字,并进行校验,非数字给出错误提示,然后重新等待用户输入。

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

#!/usr/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 eachLine 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.usr.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[]用法练习


#!/usr/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.argv1

** **

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迭代查找目录下文件


#两种方法

#!/usr/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那列,然后求和)

#!/usr/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检测一次。

#!/usr/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')

#!/usr/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,则输出信息没有这个用户;

#!/usr/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:

print 'Match item: ' , line

match = 1

if match == 0 :

print 'No match item found!'

else: print "Sorry ,user %s not found " %input

十、Python监控CPU情况

1、实现原理:通过SNMP协议获取系统信息,再进行相应的计算和格式化,最后输出结果

2、特别注意:被监控的机器上需要支持snmp。yum install -y net-snmp*安装

"""

#!/usr/bin/python

import os

def getAllitems(host, oid):

sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid + '|grep Raw|grep Cpu|grep -v Kernel').read().split('\n')[:-1]

return sn1

def getDate(host):

items = getAllitems(host, '.1.3.6.1.4.1.2021.11')

date = []

rate = []

cpu_total = 0

#us = us+ni, sy = sy + irq + sirq

for item in items:

float_item = float(item.split(' ')[3])

cpu_total += float_item

if item == items[0]:

date.append(float(item.split(' ')[3]) + float(items[1].split(' ')[3]))

elif item == item[2]:

date.append(float(item.split(' ')[3] + items[5].split(' ')[3] + items[6].split(' ')[3]))

else:

date.append(float_item)

#calculate cpu usage percentage

for item in date:

rate.append((item/cpu_total)*100)

mean = ['%us','%ni','%sy','%id','%wa','%cpu_irq','%cpu_sIRQ']

#calculate cpu usage percentage

result = map(None,rate,mean)

return result

if name == 'main':

hosts = ['192.168.10.1','192.168.10.2']

for host in hosts:

print '==========' + host + '=========='

result = getDate(host)

print 'Cpu(s)',

#print result

for i in range(5):

print ' %.2f%s' % (resulti,resulti),

print

print

十一、Python监控网卡流量

1、实现原理:通过SNMP协议获取系统信息,再进行相应的计算和格式化,最后输出结果

2、特别注意:被监控的机器上需要支持snmp。yum install -y net-snmp*安装

"""

#!/usr/bin/python

import re

import os

#get SNMP-MIB2 of the devices

def getAllitems(host,oid):

sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')[:-1]

return sn1

#get network device

def getDevices(host):

device_mib = getAllitems(host,'RFC1213-MIB::ifDescr')

device_list = []

for item in device_mib:

if re.search('eth',item):

device_list.append(item.split(':')[3].strip())

return device_list

#get network date

def getDate(host,oid):

date_mib = getAllitems(host,oid)[1:]

date = []

for item in date_mib:

byte = float(item.split(':')[3].strip())

date.append(str(round(byte/1024,2)) + ' KB')

return date

if name == 'main':

hosts = ['192.168.10.1','192.168.10.2']

for host in hosts:

device_list = getDevices(host)

inside = getDate(host,'IF-MIB::ifInOctets')

outside = getDate(host,'IF-MIB::ifOutOctets')

print '==========' + host + '=========='

for i in range(len(inside)):

print '%s : RX: %-15s TX: %s ' % (device_list[i], inside[i], outside[i])

print

Python运维中常用的_脚本的更多相关文章

  1. Apache运维中常用功能配置笔记梳理

    Apache 是一款使用量排名第一的 web 服务器,LAMP 中的 A 指的就是它.由于其开源.稳定.安全等特性而被广泛使用.下边记录了使用 Apache 以来经常用到的功能,做此梳理,作为日常运维 ...

  2. python运维开发常用模块(四)文件对比模块difflib

    1.difflib介绍 difflib作为 Python的标准库模块,无需安装,作用是对比文本之间的差异,且支持 输出可读性比较强的HTML文档,与Linux下的diff命令相似.我们可以 使用dif ...

  3. python运维开发常用模块(6)发送电子邮件模块smtplib

    1.模块常用方法 SMTP类定义:smtplib.SMTP([host[,port[,local_hostname[, timeout]]]]),作为SMTP的构造函数,功能是与smtp服务器建立连接 ...

  4. python运维开发常用模块(一)psutil

    1.模块简介 psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻 松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网 络等)信息.它主 ...

  5. linux运维中常用的指令

    一.终端中常用的快捷键 man界面中的快捷键: ?keyword                 向上搜索关键词keyword,n向下搜索,N继续向上搜索 /keyword   向下搜索关键词keyw ...

  6. Python运维中20个常用的库和模块

    1.psutil是一个跨平台库(https://github.com/giampaolo/psutil) 能够实现获取系统运行的进程和系统利用率(内存,CPU,磁盘,网络等),主要用于系统监控,分析和 ...

  7. python运维开发常用模块(8)EXCEL操作模块XlsxWriter

    1.excel介绍 Excel是当今最流行的电子表格处理软件,支持丰富的计算函数及 图表,在系统运营方面广泛用于运营数据报表,比如业务质量.资源利 用.安全扫描等报表,同时也是应用系统常见的文件导出格 ...

  8. python运维开发常用模块(7)web探测模块pycurl

    1.模块介绍 pycurl(http://pycurl.sourceforge.net)是一个用C语言写的libcurl Python实现,功能非常强大,支持的操作协议有FTP.HTTP.HTTPS. ...

  9. python运维开发常用模块(5)文件目录对比模块filecmp

    1.filecmp模块介绍 当我们进行代码审计或校验备份结果时,往往需要检查原始与目 标目录的文件一致性,Python的标准库已经自带了满足此需求的模块 filecmp.filecmp可以实现文件.目 ...

随机推荐

  1. __getattr__在python2.x与python3.x中的区别及其对属性截取与代理类的影响

    python2.x中的新类型类(New-style class)与python3.x的类一致,均继承object类,而不继承object的类称为经典类(classic class),而对于这两种类,一 ...

  2. ACM&OI 基础数学算法专题

    [前言] 本人学习了一定时间的算法,主要精力都花在数学类的算法上面 而数学类的算法中,本人的大部分精力也花费在了数论算法上 此类算法相对抽象,证明过程比较复杂 网络上的博客有写得非常好的,但也有写得不 ...

  3. 【Linux】Linux中的网络命令

    dig命令:是常用的域名查询工具,可以用来测试域名系统工作是否正常. 语法: dig(选项)(参数) [root@localhost tmp]# dig http://oa.kingnet.com ; ...

  4. Python中Opencv和PIL.Image读取图片的差异对比

    近日,在进行深度学习进行推理的时候,发现不管怎么样都得不出正确的结果,再仔细和正确的代码进行对比了后发现原来是Python中不同的库读取的图片数组是有差异的. image = np.array(Ima ...

  5. 72)MFC测试动态共享库

    动态共享库: 首先我建立一个新的动态库: 然后不选择空项目了,因为我们普通的cpp文件 入口是main  win32入口是winmain  那么这个动态库的入口在哪里  我们就是为了看一看: 出来这样 ...

  6. 吴裕雄--天生自然 JAVASCRIPT开发学习: 表单验证

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  7. Java学习十五

    学习内容: MyBaits 以前从来没有接触过mybatis,通过今天的学习知道这是一个框架,适用于关注SQL优化和需要频繁更新的项目. 今天做一个关于mybatis项目的入门小程序,效果很不理想. ...

  8. 解决Android Studio的安装问题

    今天开始了android studio的下载与安装,我再官网上下载了Android studio,下载不难,运行出来可需要一定的时间,在中途中我遇到了一些问题 一:Build错误: 在我最开始下载完A ...

  9. Python说文解字_继承过程中的参数集合

    1. 先看一段属性继承的代码: class User: def __init__(self,name,age): self.name = name self.age = age class User1 ...

  10. c语言的各种技巧

    一.参考网址 1.参考网址1:C 语言的奇技淫巧 二.