范文资料网>反思报告>脚本>《python运维脚本实例

python运维脚本实例

时间:2022-09-24 04:35:14 脚本 我要投稿
  • 相关推荐

python运维脚本实例

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") #如果要写入字符串以外的数据,先将他转换为字符串.

http://www.ahsrst.cnl() 返回一个整数,表示当前文件指针的位置(就是到文件头的比特数).

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) 

《python运维脚本实例》全文内容当前网页未完全显示,剩余内容请访问下一页查看。

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

二、写程序打印三角形

#!/usr/bin/env python

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

for i inrange(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'

四、请按照这样的日期格式(xx-xx-xx-xx)每日生成一个文件,例如今天生成的文件为2017-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()

str1 = ''.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 = http://www.ahsrst.cnunt(j) 

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

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

2. 根据用户输入数字,输出从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):

《python运维脚本实例》全文内容当前网页未完全显示,剩余内容请访问下一页查看。

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 noteachline.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.ahsrst.cn',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()

iflen(sys.argv)< 2:

print "no function be setted."

sys.exit()

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

#两种方法

#!/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 sendsi-mp-lemail (warning):

msg = mimetext(warning)

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

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

try:

smtp =smtplib.smtp()

http://www.ahsrst.cnnnect(r'http://www.ahsrst.cn')

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 启动成功'

sendsi-mp-lemail(warning = "this is a warning!!!")#调用函数

else:

print 'httpd正常'

time.sl-ee-p(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 se-le-ct 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 se-le-ct 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' % (result[i][0],result[i][1]),

print

print

python监控系统负载

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).read().split('\n')

return sn1

def getload(host,loid):

load_oids = '1.3.6.1.4.1.2021.10.1.3.' + str(loid)

return getallitems(host,load_oids)[0].split(':')[3]

if __name__ == '__main__':

hosts = ['192.168.10.1','192.168.10.2']

#check_system_load

print '==============system load=============='

for host in hosts:

load1 = getload(host, 1)

load10 = getload(host, 2)

load15 = getload(host, 3)

print '%s load(1min): %s ,load(10min): %s ,load(15min): %s' % (host,load1,load10,load15)

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:

ifre.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、实现原理:通过snmp协议获取系统信息,再进行相应的计算和格式化,最后输出结果

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

"""

#!/usr/bin/python

import re

import os

def getallitems(host,oid):

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

return sn1

def getdate(source,newitem):

for item in source[5:]:

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

return newitem

def getrealdate(item1,item2,listname):

for i in range(len(item1)):

listname.append(int(item1[i])*int(item2[i])/1024)

return listname

def caculatediskusedrate(host):

hrstoragedescr = getallitems(host, 'host-resources-mib::hrstoragedescr')

hrstorageused = getallitems(host, 'host-resources-mib::hrstorageused')

hrstoragesize = getallitems(host, 'host-resources-mib::hrstoragesize')

hrstorageallocationunits = getallitems(host, 'host-resources-mib::hrstorageallocationunits')

disk_list = []

hrsused = []

hrsize = []

hrsaunits = []

#get disk_list

for item in hrstoragedescr:

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

disk_list.append(item.split(':')[3])

#print disk_list      

getdate(hrstorageused,hrsused)

getdate(hrstoragesize,hrsize)

#print getdate(hrstorageallocationunits,hrsaunits)

#get hrstorageallocationunits

for item in hrstorageallocationunits[5:]:

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

#caculate the result

#disk_used = hrstorageused * hrstorageallocationunits /1024 (kb)

disk_used = []

total_size = []

disk_used = getrealdate(hrsused,hrsaunits,disk_used)

total_size = getrealdate(hrsize,hrsaunits,total_size)

diskused_rate = []

for i in range(len(disk_used)):

diskused_rate.append(str(round((float(disk_used[i])/float(total_size[i])*100), 2)) + '%')

return diskused_rate,disk_list

if __name__ == '__main__':

hosts = ['192.168.10.1','192.168.10.2']

for host in hosts:

result = caculatediskusedrate(host)

diskused_rate = result[0]

partition = result[1]

print "==========",host,'=========='

for i in range(len(diskused_rate)):

print '%-20s used: %s' % (partition[i],diskused_rate[i])

print

python监控内存(swap)的使用率

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).read().split('\n')[:-1]

return sn1

def getswaptotal(host):

swap_total = getallitems(host, 'ucd-snmp-mib::memtotalswap.0')[0].split(' ')[3]

return swap_total

def getswapused(host):

swap_avail = getallitems(host, 'ucd-snmp-mib::memavailswap.0')[0].split(' ')[3]

swap_total = getswaptotal(host)

swap_used =str(round(((float(swap_total)-float(swap_avail))/float(swap_total))*100 ,2)) + '%'

return swap_used

def getmemtotal(host):

mem_total = getallitems(host, 'ucd-snmp-mib::memtotalreal.0')[0].split(' ')[3]

return mem_total

def getmemused(host):

mem_total = getmemtotal(host)

mem_avail = getallitems(host, 'ucd-snmp-mib::memavailreal.0')[0].split(' ')[3]

mem_used =str(round(((float(mem_total)-float(mem_avail))/float(mem_total))*100 ,2)) + '%'

return mem_used

if __name__ == '__main__':

hosts = ['192.168.10.1','192.168.10.2']

print "monitoring memory usage"

for host in hosts:

mem_used = getmemused(host)

swap_used = getswapused(host)

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

print 'mem_used = %-15s   swap_used = %-15s' % (mem_used, swap_used)

print

python运维脚本 生成随机密码

#!/usr/bin/env python

# -*- coding=utf-8 -*-

#using gpl v2.7

#author: http://www.ahsrst.cn

import random, string       #导入random和string模块

def genpassword(length):

#随机出数字的个数

numofnum = random.randint(1,length-1)

numofletter = length - numofnum

#选中numofnum个数字

slcnum = [random.choice(string.digits) for i in range(numofnum)]

#选中numofletter个字母

slcletter = [random.choice(string.ascii_letters) for i in range(numofletter)]

#打乱组合

slcchar = slcnum + slcletter

random.shuffle(slcchar)

#生成随机密码

getpwd = ''.join([i for i in slcchar])

return getpwd

if __name__ == '__main__':

print genpassword(6)

#!/usr/bin/env python

import random

import string

import sys

similar_char = '0ooii1lpp'

upper = ''.join(set(string.uppercase) - set(similar_char))

lower = ''.join(set(string.lowercase) - set(similar_char))

symbols = '!#$%&\*+,-./:;=?@^_`~'

numbers = '123456789'

group = (upper, lower, symbols, numbers)

def getpass(lenth=8):

pw = [random.choice(i) for i in group]

con = ''.join(group)

for i in range(lenth-len(pw)):

pw.append(random.choice(con))

random.shuffle(pw)

return ''.join(pw)

genpass = getpass(int(sys.argv[1]))

print genpass

#!/usr/bin/env python

import random

import string

def genpassword(length):

chars=string.ascii_letters+string.digits

return ''.join([random.choice(chars) for i in range(length)])

if __name__=="__main__":

for i in range(10):

print genpassword(15) 

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

'''

简短地生成随机密码,包括大小写字母、数字,可以指定密码长度

'''

#生成随机密码

from random import choice

import string

#python3中为string.ascii_letters,而python2下则可以使用string.letters和string.ascii_letters

def genpassword(length=8,chars=string.ascii_letters+string.digits):

return ''.join([choice(chars) for i in range(length)])

if __name__=="__main__":

#生成10个随机密码    

for i in range(10):

#密码的长度为8

print(genpassword(8))

#!/usr/bin/env python

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

#导入random和string模块

import random, string

def genpassword(length):

#随机出数字的个数

numofnum =random.randint(1,length-1)

numofletter = length - numofnum

#选中numofnum个数字

slcnum = [random.choice(string.digits) for i in range(numofnum)]

#选中numofletter个字母

slcletter = [random.choice(string.ascii_letters) for i in range(numofletter)]

#打乱这个组合

slcchar = slcnum + slcletter

random.shuffle(slcchar)

#生成密码

genpwd = ''.join([i for i in slcchar])

return genpwd

if __name__ == '__main__':

print genpassword(6)

利用random生成6位数字加字母随机验证码

import random

li = []

for i in range(6):

r = random.randrange(0, 5)

if r == 2 or r == 4:

num = random.randrange(0, 9)

li.append(str(num))

else:

temp = random.randrange(65, 91)

c = chr(temp)

li.append(c)

result = "".join(li)  # 使用join时元素必须是字符串

print(result)

输出

335hqs

vs6rn5

...

random.random()用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成随机数

n: a <= n <= b。如果 a <b, 则 b <= n <= a。

print random.uniform(10, 20)  

print random.uniform(20, 10)  

#---- 

#18.7356606526  

#12.5798298022  

random.randint 用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,python生成随机数

print random.randint(12, 20) #生成的随机数n: 12 <= n <= 20 

print random.randint(20, 20) #结果永远是20 

#print random.randint(20, 10) #该语句是错误的。 

下限必须小于上限。

random.randrange 从指定范围内,按指定基数递增的集合中 

random.randrange的函数原型为:random.randrange([start], stop[, step]),从指定范围内,按指定基数递增的集合中 获取一个随机数。

如:

random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。

random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效

随机整数:

>>> import random

>>> random.randint(0,99)

21

随机选取0到100间的偶数:

>>> import random

>>> random.randrange(0, 101, 2)

42

随机浮点数:

>>> import random

>>> random.random() 

0.85415370477785668

>>>random.uniform(1, 10)

5.4221167969800881

随机字符:

random.choice从序列中获取一个随机元素

其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型

这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。

list, tuple, 字符串都属于sequence。

print random.choice("学习python")   

print random.choice(["jgood", "is", "a", "handsome", "boy"])  

print random.choice(("tuple", "list", "dict"))  

>>> import random

>>> random.choice('abcdefg&#%^*f')

'd'

多个字符中选取特定数量的字符:

random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断

sample函数不会修改原有序列。

>>> import random

random.sample('abcdefghij',3) 

['a', 'd', 'b']

多个字符中选取特定数量的字符组成新字符串:

>>> import random

>>> import string

>>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r

eplace(" ","")

'fih'

随机选取字符串:

>>> import random

>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )

'lemon'

洗牌:

random.shuffle的函数原型为:random.shuffle(x[, random]),用于将一个列表中的元素打乱 .

>>> import random

>>> items = [1, 2, 3, 4, 5, 6]

>>> random.shuffle(items)

>>> items

[3, 2, 5, 6, 4, 1]

1、random.random

random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0

2、random.uniform

random.uniform(a, b),用于生成一个指定范围内的随机符点数

两个参数其中一个是上限,一个是下限。

如果a < b,则生成的随机数n: b>= n >= a。

如果 a >b,则生成的随机数n: a>= n >= b。

print random.uniform(10, 20)

print random.uniform(20, 10)

# 14.73

# 18.579 

3、random.randint

random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b

print random.randint(1, 10)

4、random.randrange

random.randrange([start], stop[, step]),从指定范围内,按指定基数递增的集合中 获取一个随机数。

如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。

5、random.choice

random.choice从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。

这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。

print random.choice("python")

print random.choice(["jgood", "is", "a", "handsome", "boy"])

print random.choice(("tuple", "list", "dict")) 

6、random.shuffle

random.shuffle(x[, random]),用于将一个列表中的元素打乱

如:

p = ["python", "is", "powerful", "si-mp-le", "and so on..."]

random.shuffle(p)

print p

# ['powerful', 'si-mp-le', 'is', 'python', 'and so on...'] 

7、random.sample

random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

例如:

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12]

slice = random.sample(list, 6)  # 从list中随机获取6个元素,作为一个片断返回

print slice

print list  # 原有序列并没有改变

round取相邻整数

print(round(1.4))

print(round(1.8))

输出:

1

2

查看各个进程读写的磁盘io

#!/usr/bin/env python

# -*- coding=utf-8 -*-

import sys

import os

import time

import signal

import re

class diskio:

def __init__(self, pname=none, pid=none, reads=0, writes=0):

self.pname = pname

self.pid = pid

self.reads = 0

self.writes = 0

def main():

argc = len(sys.argv)

if argc != 1:

print "usage: please run this script like [./diskio.py]"

sys.exit(0)

if os.getuid() != 0:

print "error: this script must be run as root"

sys.exit(0)

signal.signal(signal.sigint, signal_handler)

os.system('echo 1 > /proc/sys/vm/block_dump')

print "task              pid       read      write"

while true:

os.system('dmesg -c > /tmp/diskio.log')

l = []

f = open('/tmp/diskio.log', 'r')

line = f.readline()

while line:

m =re.match(\

'^(\s+)\((\d+)\): (read|write) block (\d+) on (\s+)', line)

if m != none:

if not l:

l.append(diskio(m.group(1), m.group(2)))

line = f.readline()

continue

found = false

for item in l:

if item.pid == m.group(2):

found = true

if m.group(3) == "read":

item.reads = item.reads + 1

elif m.group(3) == "write":

item.writes = item.writes + 1

if not found:

l.append(diskio(m.group(1), m.group(2)))

line = f.readline()

time.sl-ee-p(1)

for item in l:

print "%-10s %10s %10d %10d" % \

(item.pname, item.pid, item.reads, item.writes)

def signal_handler(signal, frame):

os.system('echo 0 > /proc/sys/vm/block_dump')

sys.exit(0)

if __name__=="__main__":

main()

python自动化运维之简易ssh自动登录

#!/usr/bin/env python

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

import pexpect

import sys

ssh = pexpect.spawn('ssh root@192.168.20.103 ')

fout = file('sshlog.txt', 'w')

ssh.logfile = fout

ssh.expect("root@192.168.20.103's password:")

ssh.sendline("yzg1314520")

ssh.expect('#')

ssh.sendline('ls /home')

ssh.expect('#')

python运维-获取当前操作系统的各种信息

#通过python的psutil模块,获取当前系统的各种信息(比如内存,cpu,磁盘,登录用户等),并将信息进行备份

# coding=utf-8

# 获取系统基本信息

import sys

import psutil

import time

import os 

#获取当前时间

time_str =  time.strftime( "%y-%m-%d", time.localtime( ) )

file_name = "./" + time_str + ".log"

ifos.path.exists ( file_name ) == false :

os.mknod( file_name )

handle = open ( file_name , "w" )

else :

handle = open ( file_name , "a" )

#获取命令行参数的个数

if len( sys.argv ) == 1 :

print_type = 1

else :

print_type = 2

def isset ( list_arr , name ) :

if name in list_arr :

return true

else :

return false

print_str = "";

#获取系统内存使用情况

if ( print_type == 1 ) or isset( sys.argv,"mem" )  :

memory_convent = 1024 * 1024

mem = psutil.virtual_memory()

print_str +=  " 内存状态如下:\n" 

print_str = print_str + "   系统的内存容量为: "+str( http://www.ahsrst.cn( memory_convent ) ) + " mb\n" 

print_str = print_str + "   系统的内存以使用容量为: "+str( http://www.ahsrst.cn( memory_convent ) ) + " mb\n" 

print_str = print_str + "   系统可用的内存容量为: "+str( http://www.ahsrst.cn( memory_convent ) - http://www.ahsrst.cn( 1024*1024 )) + "mb\n"

print_str = print_str + "   内存的buffer容量为: "+str( http://www.ahsrst.cn( memory_convent ) ) + " mb\n" 

print_str = print_str + "   内存的cache容量为:" +str( http://www.ahsrst.cn( memory_convent ) ) + " mb\n"

#获取cpu的相关信息

if ( print_type == 1 ) or isset( sys.argv,"cpu" ) :

print_str += " cpu状态如下:\n"

cpu_status = psutil.cpu_times()

print_str = print_str + "   user = " + str( cpu_http://www.ahsrst.cner ) + "\n" 

print_str = print_str + "   nice = " + str( cpu_status.nice ) + "\n"

print_str = print_str + "   system = " + str( cpu_status.system ) + "\n"

print_str = print_str + "   idle = " + str ( cpu_status.idle ) + "\n"

print_str = print_str + "   iowait = " + str ( cpu_status.iowait ) + "\n"

print_str = print_str + "   irq = " + str( cpu_status.irq ) + "\n"

print_str = print_str + "   softirq = " + str ( cpu_status.softirq ) + "\n" 

print_str = print_str + "   steal = " + str ( cpu_status.steal ) + "\n"

print_str = print_str + "   guest = " + str ( cpu_status.guest ) + "\n"

#查看硬盘基本信息

if ( print_type == 1 ) or isset ( sys.argv,"disk" ) :

print_str +=  " 硬盘信息如下:\n" 

disk_status = psutil.disk_partitions()

for item in disk_status :

print_str = print_str + "   "+ str( item ) + "\n"

#查看当前登录的用户信息

if ( print_type == 1 ) or isset ( sys.argv,"user" ) :

print_str +=  " 登录用户信息如下:\n " 

user_status = http://www.ahsrst.cners()

for item in  user_status :

print_str = print_str + "   "+ str( item ) + "\n"

print_str += "---------------------------------------------------------------\n"

print ( print_str )

handle.write( print_str )

handle.close()

python自动化运维学习笔记

psutil  跨平台的ps查看工具

执行pip install psutil 即可,或者编译安装都行。

# 输出内存使用情况(以字节为单位)

import psutil

mem = psutil.virtual_memory()

print mem.total,http://www.ahsrst.cned,mem

print psutil.swap_memory()  # 输出获取swap分区信息

# 输出cpu使用情况

cpu = psutil.cpu_stats()

http://www.ahsrst.cnerrupts,cpu.ctx_switches

psutil.cpu_times(percpu=true)      # 输出每个核心的详细cpu信息

psutil.cpu_times().user              # 获取cpu的单项数据 [用户态cpu的数据]

psutil.cpu_count()                   # 获取cpu逻辑核心数,默认logical=true

psutil.cpu_count(logical=false) # 获取cpu物理核心数

# 输出磁盘信息

psutil.disk_partitions()         # 列出全部的分区信息

psutil.disk_usage('/')               # 显示出指定的挂载点情况【字节为单位】

psutil.disk_io_counters()       # 磁盘总的io个数

psutil.disk_io_counters(perdisk=true)  # 获取单个分区io个数

# 输出网卡信息

http://www.ahsrst.cn_io_counter() 获取网络总的io,默认参数pernic=false

http://www.ahsrst.cn_io_counter(pernic=ture)获取网络各个网卡的io

# 获取进程信息

psutil.pids()     # 列出所有进程的pid号

p = psutil.process(2047)

p.name()   列出进程名称

p.exe()    列出进程bin路径

p.cwd()    列出进程工作目录的绝对路径

p.status()进程当前状态[sl-ee-p等状态]

p.create_time()   进程创建的时间 [时间戳格式]

p.uids()

p.gids()

p.cputimes()  【进程的cpu时间,包括用户态、内核态】

p.cpu_affinity()  # 显示cpu亲缘关系

p.memory_percent()   进程内存利用率

p.meminfo()   进程的rss、vms信息

p.io_counters()   进程io信息,包括读写io数及字节数

http://www.ahsrst.cnnnections()   返回打开进程socket的namedutples列表

p.num_threads()   进程打开的线程数

#下面的例子中,popen类的作用是获取用户启动的应用程序进程信息,以便跟踪程序进程的执行情况

import psutil

from subprocess import pipe

p =psutil.popen(["/usr/bin/python" ,"-c","print 'helloworld'"],stdout=pipe)

p.name()

http://www.ahsrst.cnername()

http://www.ahsrst.cnmmunicate()

p.cpu_times()

# 其它

http://www.ahsrst.cners()    # 显示当前登录的用户,和linux的who命令差不多

# 获取开机时间

psutil.boot_time() 结果是个unix时间戳,下面我们来转换它为标准时间格式,如下:

datetime.datetime.fromtimestamp(psutil.boot_time())  # 得出的结果不是str格式,继续进行转换 datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%y-%m-%d%h:%m:%s')

【python运维脚本实例】相关文章:

运维述职报告02-08

运维值班制度04-22

机房运维总结03-24

运维单位汇报材料09-22

it运维岗位职责05-02

运维工作计划02-13

运维总监岗位的职责02-13

运维部述职报告02-06

运维工作总结02-05