一、用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, οnerrοr=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]),
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])
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])
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)
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
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+)(\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')