用Python管理数据库
这里使用一个监控主机的内存和硬盘的使用来将这里的基础操作全部介绍
- 这里有二个文件,第一个文件是收集到系统的信息
#这些代码没有什么好说的,用os模块操作Linux系统得到你要的相关信息
#!/bin/python
import os
class HostInfo(object):
def getMem(self):
#注意这里不使用os.system是有原因的因为,system总会返回None和0,使我们看起来不方便
f = os.popen("free -m | grep Mem | awk '{print $3}'")
return f.read()
def getDisk(self):
f = os.popen("df -h | head -2 | tail -1 | awk '{print $5}'")
return f.read()
def getIP(self):
f = os.popen("ifconfig br0 | grep inet | grep -v inet6 | awk '{print $2}'")
return f.read()
if __name__ == "__main__":
h=HostInfo()
h.getMem()
h.getDisk()
h.getIP()
- 得到系统的内存信息和硬盘信息存储到数据库中,注意在导入MySQLdb 这个模块时需要安装MySQL-python这个软件。
#!/bin/python
import jiankong
#导入上面这个自定义的模块
import MySQLdb as mysql
import time
#这是一个简单的函数,得到上面统计到的信息
def get_info():
h = jiankong.HostInfo()
mem = h.getMem().strip()
disk = h.getDisk().strip()
ip = h.getIP().strip()
return mem,disk,ip
def save_info():
#连接数据库
conn = mysql.connect(user="root",passwd="1234",host="localhost",db="feitian")
cur = conn.cursor()
try:
#这里防止在第二次执行该脚本时会出现错误,用try语句让程序继续执行
cur.execute("create table lala(ip varchar(20),mem int,disk varchar(20),time int)")
except Exception,e:
#让程序每隔五秒就对系统的信息进行一次统计
while True:
mem, disk, ip = get_info()
sqli = 'insert into lala values(%s,%s,%s,%s)'
cur.execute(sqli,(ip,mem,disk,time.time()))
time.sleep(5)
conn.commit()
cur.close()
conn.close()
save_info()
#注意:这里在用sqli进行存储数据的时候可以用一个字典进行一次多条信息进行存储,可以节省系统资源
异常
Python中异常的处理机制:try……except……finally
- try:将可能出潜在的代码放在try语句中,try语句块中一旦出现错误,try语句块后面的的代码就不在执行。
- except:错误类型,变量名,错误处理的代码
- finally:不管try中会不会出现异常,他都会执行finally中的语句
总结一下,就是当try语句块中出现错误,刚好是except捕获的错误类型,执行执行错误代码,否则直接报错
举个例子
try:
print a
except NameError,e:
print "程序还继续执行"
print "错误类型 %s"%(e)
finally:
print "不管有没有异常,我都会被执行"
print "总算执行完了"
结果:
程序还继续执行
错误类型 name 'a' is not defined
不管有没有异常,我都会被执行
总算执行完了
raise异常
- 和try异常不同的是,如果程序出现raise异常程序不会继续执行。他是人为抛出的,在程序员认为这里出现错误会影响整个程序的运行的地方使用。
class AgeError(IOError):
pass
age = input()
if age < 0 or age >200:
raise AgeError
print "hello"
#注意这个程序如果你输入大于200和小于0的数,他就会引发raise异常,他是系统级别的,直接中断程序执行,hello就不会被打印出来。
用Python进行文件的差异比较
用到的模块是difflib模块,在使用之前要导入模块
第一种:使用difflib.Differ()方法对字符串进行比较
import difflib
text1 = 'hello westos'
text2 = 'hello zhan'
text1_lines = text1.splitlines()
text2_lines = text2.splitlines()
# 创建diff对象
d = difflib.Differ()
# 采用compare方法对字符串进行比较
diff = d.compare(text1_lines, text2_lines)
# print list(diff)
print '\n'.join(list(diff))
结果:
- hello westos
+ hello zhan
- ‘-’ 包含在第一个中,但不包含在第二个中
- ‘+’ 包含在第二个中,但不包含在第一个中
- ’ ’ 两者相同
- ‘?’ 两个存在增量差异
- ‘^’ 标志出两者行存在的差异字符
第二种:使用difflib.HtmlDiff()方法比较
这种方法会生成一个html文件,用浏览器打开就可清楚的看到两个文件的不同
import difflib
import sys
first_file = sys.argv[1]
second_file = sys.argv[2]
with open(first_file) as f :
test1 = f.read()
with open(second_file) as b:
test2 = b.read()
test1 = test1.splitlines()
test2 = test2.splitlines()
d =difflib.HtmlDiff()
print d.make_file(test1,test2)
JSON模块
json作用
- json模块是JavaScript Object Natation的简称,轻量级的文件交换模式-
- 这里举一个简单的例子
json.dumps
将Python的数据类型序列化为字符串
import json
dic = {"ftp":22,"http":80}
print "dic的类型是",type(dic)
jdic = json.dumps(dic)
print "jdic的类型是",type(jdic)
结果:
dic的类型是 <type 'dict'>
jdic的类型是 <type 'str'>
json.dump
将Python的数据类型序列化到某个文件对象中
#!/bin/python
import json
dic={"fep":22,"http":80,"service":"http"}
json.dump(dic,open("my.json","w"),indent = 4)
#indent=4表示缩进的意思
lala = "laf"
s = json.load(open("my.json","a+"))
json.l
my.json的文件内容,也就是输出结果:
{
"http": 80,
"service": "http",
"fep": 22
}
json.loads()还原转换
import json
dic = {"ftp":22,"http":80}
jdic = json.dumps(dic)
dic = json.loads(jdic)
print type(dic)
结果:
<type 'dict'>
json.load()对文件进行还原
import json
with open("my.json",'r')as f :
data = json.load(f)
正则表达式
正则表达式中的通配符
- ^,$,*,?,[abc],[^abc],{1..2},[[:digit:]]等等,他和Linux中的通配符,可以看着这里:http://13132323.blog.51cto.com/13122323/1948006
正则表达式
re (regular expression)
正则表达式的的匹配符
常量
import re
s = r"hello"
re.findall(s,"aabbhellocchello")
以什么开头和结尾(^,$)
- 有一个列表l = [“hello”,”world”,”good”],找出列表中以h开头的字符串;
l=["hello","word","good"]
s = r"^h"
for i in l:
if re.findall(s,i) != []:
print i
[],[^abc]
s = r"t[oa]"
re.findall(s,st)
Out[19]: ['to', 'ta']
特殊转义符
\d # 匹配单个数字,[0123456789]
\D # 除了数字,[^0123456789]
\w # 匹配字母,数字,或者下划线
\W # 匹配除了字母,数字,或者下划线之外的
\s # 匹配空格,\t,\n,\r
\S #
题目: 判断一个变量名是否合法? 判断第一个字符是否为字母或者下划线,后面的是否为字母,下划线或者数字;
import re
import string
name = raw_input("please input a naem:")
name_first = name[0]
name_nest = name[1:]
s = r"\w"
b = r"\d"
if re.findall(b,name_first):
print "it not illeagl"
for i in name_nest:
if re.findall(s,i):
pass
else:
print "it not illeagl"
break
重复次数
{m,n} 重复m次到n次 ,[m,n] m=<count<=n
{m,} 重复m次到无限次
{0,} *
{1,} +
{0,1} ?
练习: 判断一个电话是否为同一个区010-12345678(前提他是电话号码)
用上面的例子:
import re
s = r"^010-{0,1}\d{8}"
re.findall(s,"你想判断的字符串")
#也可以用下面的替代
s = r"^010-+\d{8}"
socket编程
- 这段代码可以实现像ssh的功能
服务端:socket_server.py文件
#!/usr/bin/env python
#coding:utf-8
'''
@author:guofan
@file:socket-server.py
@contact:xc_guofan@163.com
@time:9/16/17 5:02 PM
@desc:
'''
import socket
# 1. 创建一个socket对象;
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 2. 并绑定服务端端口,并且时刻监听
server.bind(("172.25.254.29",8887))
server.listen(5)
print "server is listening......"
try:
while True:
# 3. 接收客户端的连接与IP:port
conn,addr = server.accept()
# 4. 给客户端发送数据;
#conn.send("hello client")
# 5. 接收客户端发送的数据
recv_data = conn.recv(1024)
import os
conn.send(os.popen(recv_data).read())
except Exception,e:
print e
finally:
# 6. 关闭连接
server.close()
if __name__ == "__main__":
pass
客户端操作:socket_client.py
#!/usr/bin/env python
# coding:utf-8
'''
@author:guofan
@file:socket-client.py
@contact:xc_guofan@163.com
@time:9/16/17 5:02 PM
@desc:
'''
import socket
# 1. 创建socket对象
client = socket.socket()
try:
# 2. 连接服务端
client.connect(("172.25.254.29", 8887))
while True:
# 3. 接收服务端的消息
#recv_data = client.recv(1024)
#print recv_data
# 4. 发送消息给服务端
command = raw_input(">>:")
client.send(command)
print client.recv(1024)
except Exception, e:
print e
finally:
# 5. 关闭连接
client.close()
if __name__ == "__main__":
pass