1. 程式人生 > >python常用運維腳本實例

python常用運維腳本實例

監控系統 用戶態 view sdi 用戶信息 日期 文件讀取 郵件通知 r+

基礎知識

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)每日生成一個文件,例如今天生成的文件為2013-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 = list.count(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):

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://search.51job.com/jobsearch/advance_search.php‘,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.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 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‘ % (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:

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、實現原理:通過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: [email protected]

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)

利用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", "simple", "and so on..."]

    random.shuffle(p)

    print p

    # [‘powerful‘, ‘simple‘, ‘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 # 原有序列並沒有改變

1.生成隨機整數:

random.randint(a,b)


random.randint(a,b) #返回一個隨機整數,範圍是a <=x <= b
>>> random.randint(888,999)
897
>>> random.randint(888,999)
989
>>> random.randint(888,999)
995


random.randrange(start, stop[, step]) #返回指定範圍的整數
>>> random.randrange(2,20,2)
6
>>> random.randrange(2,20,2)
4
>>> random.randrange(2,20,2)
14
2.浮點數


random.random() #返回一個浮點數,範圍是0.0 到1.0
>>> random.random()
0.22197993728352594
>>> random.random()
0.8683996624230081
>>> random.random()
0.29398514954873434


random.uniform(a,b)#返回一個指定範圍的浮點數
>>> random.uniform(1, 10)
3.0691737651343636
>>> random.uniform(1, 10)
9.142357395475619
>>> random.uniform(1, 10)
6.927435868405478


3.隨機序列


random.choice()#從非空序列中返回一個隨機元素
>>> name
[‘du‘, ‘diao‘, ‘han‘, ‘jiang‘, ‘xue‘]
>>> random.choice(name)
‘xue‘
>>> random.choice(name)
‘xue‘
>>> random.choice(name)
‘du‘
>>> random.choice(name)
‘du‘
>>> random.choice(name)
‘du‘
>>> random.choice(name)
‘jiang‘


#隨機返回指定長度的子序列
>>> random.sample(name,2)
[‘xue‘, ‘du‘]
>>> random.sample(name,2)
[‘diao‘, ‘jiang‘]
>>> random.sample(name,2)
[‘xue‘, ‘du‘]


生成指定長度的隨機密碼:


[root@zhu ~]# python jiang.py
GrDUytJE
[root@zhu ~]# python jiang.py
8XaCoUTz
[root@zhu ~]# cat jiang.py

import random,string

chars=string.ascii_letters+string.digits

print ‘‘.join([random.choice(chars) for i in range(8)])

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

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.sleep(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 [email protected] ‘)

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

ssh.logfile = fout

ssh.expect("[email protected]‘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"

if os.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( mem.total/( memory_convent ) ) + " MB\n"

print_str = print_str + " 系統的內存以使用容量為: "+str( mem.used/( memory_convent ) ) + " MB\n"

print_str = print_str + " 系統可用的內存容量為: "+str( mem.total/( memory_convent ) - mem.used/( 1024*1024 )) + "MB\n"

print_str = print_str + " 內存的buffer容量為: "+str( mem.buffers/( memory_convent ) ) + " MB\n"

print_str = print_str + " 內存的cache容量為:" +str( mem.cached/( 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_status.user ) + "\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 = psutil.users()

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,mem.used,mem

print psutil.swap_memory() # 輸出獲取SWAP分區信息

# 輸出CPU使用情況

cpu = psutil.cpu_stats()

printcpu.interrupts,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個數

# 輸出網卡信息

psutil.net_io_counter() 獲取網絡總的IO,默認參數pernic=False

psutil.net_io_counter(pernic=Ture)獲取網絡各個網卡的IO

# 獲取進程信息

psutil.pids() # 列出所有進程的pid號

p = psutil.Process(2047)

p.name() 列出進程名稱

p.exe() 列出進程bin路徑

p.cwd() 列出進程工作目錄的絕對路徑

p.status()進程當前狀態[sleep等狀態]

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數及字節數

p.connections() 返回打開進程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()

p.username()

p.communicate()

p.cpu_times()

# 其它

psutil.users() # 顯示當前登錄的用戶,和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常用運維腳本實例