目录:
1、打开浏览器并登录126邮箱
2、连接mysql并新建数据库、表、插入数据
3、建立字典,给定两个长度的列表,用两个列表的所有数据组成字典
4、创建一个字典,并把这个字典中的按照字母顺序显示出来
5、一个简单的注册用户、登录、退出
6、在mysql数据库连续创建150个数据库
7、python各种类型的转换
8、python连接oracle
9、向oracle多个表定时插入数据
10、写文件输出文件初体验
11、python+splinter+iframe初体验
12、处理html页面元素的实例
13、批量增加用户
14、函数初体验
15、python+HTMLParser+urllib
16、在AIX上安装rpm包
17、在AIX上下载升级rpm包
18、整合16、17
19、改良17
20、杂
21、获取cpu_mem等
22、自定义类的调用
23、date 格式化输出
- 打开浏览器并登陆126邮箱
(ubuntu11.04 splinter官网 )
- $ wget http://pypi.python.org/packages/source/s/setuptools/setuptools-06c11.tar.gz #下载setuptools,下面安装splinter用到
- $ tar zxvf setuptools-0.6c11.tar.gz
- $ cd setuptools-0.6c11
- $ /usr/bin/python setup.py build
- $ sudo /usr/bin/python setup.py install
- $ sudo apt-get install git #获取splinter需要用到
- $ git clone git://github.com/cobrateam/splinter.git
- $ cd splinter
- $ sudo python setup.py install
- $ vi 126.py
- import time
- from splinter import Browser
- def splinter(url):
- browser = Browser()
- browser.visit(url)
- time.sleep(5)
- browser.find_by_id('idInput').fill('******')
- browser.find_by_id('pwdInput').fill('******')
- browser.find_by_id('loginBtn').click()
- time.sleep(8)
- browser.quit()
- if __name__ == '__main__':
- websize3 = 'http://www.126.com'
- splinter(websize3)
- 连接mysql并新建数据库、表、插入数据
(ubuntu12.04)
$ sudo apt-get install python-mysqldb
- import MySQLdb
- try:
- conn = MySQLdb.connect(host='localhost',user='root',passwd='password',port=3306)
- cur = conn.cursor()
- cur.execute('create database if not exists python')
- conn.select_db('python')
- cur.execute('create table test(id int,info varchar(20)')
- value = [1,'hi rollen']
- cur.execute('insert into test values(%s,%s)',value)
- conn.commit()
- cur.close()
- conn.close()
- except MySQLdb.Error,e:
- print "MySQL Error %d: %s " % (e.arrgs[0],e.args[1])
- import MySQLdb
- import random
- import itertools
- import string
- str1 = 'abcdefghijklmnopqrstuvwxyz'
- num = [1,2,3,4,5,6,7,8,9,0]
- i = 0
- try:
- conn = MySQLdb.connect(host='localhost',user='root',passwd='password',port=3306)
- cur = conn.cursor()
- # cur.execute('create database python')
- cur.execute('use python')
- # sql1 = 'create table test(id int,info varchar(20))'
- # cur.execute(sql1)
- while i < 3:
- id1 = random.randint(0,10)
- va = random.sample(str1,8)
- info = "".join(itertools.chain(*va))
- param={'id':id1,'info':info}
- ww = 'insert into test values( $id , \''+'$info \')'
- pp = string.Template(ww)
- sql2 = pp.substitute(param)
- cur.execute(sql2)
- print sql2
- i +=1
- conn.commit()
- cur.close()
- conn.close()
- except MySQLdb.Error,e:
- print "MySQL Error %d:%s" % (e.args[0],e.args[1])
- 建立字典,给定两个长度相同的列表,用两个列表的所有数据组成一个字典。
- a = [1,2,3,4,5]
- b = ['a','b','c','d','e']
- dict1= {}
- t = [0,1,2,3,4]
- for i in t:
- dict1[a[i]] = b[i]
- 创建一个字典,并把这个字典中的建按照字母顺序显示出来
- a = {'a':1,'b':2,'g':4,'o':5,'j':6,'y':3}
- sorted(a) = b
- for key in b:
- print 'key = % s,value % ' %(key,a[key])
- 一个简单的注册用户、登陆、退出
- db = {}
- def newuser():
- prompt = 'login desired:'
- while True:
- name = raw_input(prompt)
- if db.has_key(name):
- prompt = 'name taken,try another:'
- continue
- else:
- break
- pwd = raw_input('passwd:')
- db[name] = pwd
- def olduser():
- name = raw_input('login:')
- pwd = raw_input('passwd:')
- passwd = db.get(name)
- if passwd == pwd:
- print 'welcome back',name
- else:
- print 'login incorrect'
- def showmenu():
- prompt = """
- (N)ew User Login
- (E)xisting User Login
- (Q)uit
- Enter choice:"""
- done = False
- while not done:
- chosen = False
- while not chosen:
- try:
- choice = raw_input(prompt).strip()[0].lower()
- except (EOFError,KeyboardInterrupt):
- choice = 'q'
- print '\nYou picked:[%s]' % choice
- if choice not in 'neq':
- print '\nInvalid option,try again'
- else:
- chosen = True
- if choice == 'q':done = True
- if choice == 'n':newuser()
- if choice == 'e':olduser()
- if __name__ == '__main__':
- showmenu()
- 在mysql数据库连续新建150个数据库
- import MySQLdb
- import time
- try:
- conn = MySQLdb.connect(host='192.168.88.240',user='scutech',passwd='dingjia',port=3306)
- cur = conn.cursor()
- i = 0
- t = {}
- while i<150:
- t[i] = 'create database python' +str(i) +' ;'
- cur.execute(t[i])
- print t[i]
- time.sleep(5)
- i +=1
- cur.close()
- conn.close()
- except MySQLdb.Error,e:
- print "Mysql Error %d: %s" % (e.args[0],e.args[1])
- python各种类型的转换:
- int(x [,base ]) 将x转换为一个整数
- long(x [,base ]) 将x转换为一个长整数
- float(x ) 将x转换到一个浮点数
- complex(real [,imag ]) 创建一个复数
- str(x ) 将对象 x 转换为字符串
- repr(x ) 将对象 x 转换为表达式字符串
- eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
- tuple(s ) 将序列 s 转换为一个元组
- list(s ) 将序列 s 转换为一个列表
- chr(x ) 将一个整数转换为一个字符
- unichr(x ) 将一个整数转换为Unicode字符
- ord(x ) 将一个字符转换为它的整数值
- hex(x ) 将一个整数转换为一个十六进制字符串
- oct(x ) 将一个整数转换为一个八进制字符串
- python连接oracle
- import cx_Oracle
- conn = cx_Oracle.connect("system","dingjia","127.0.0.1:1521/scutech")
- c = conn.cursor()
- sql = "select name from v$datafile"
- r = c.execute(sql)
- li = r.fetchall()
- for row in li:
- print row
- 前提:需安装cx_Oracle-5.12-10g-py26-1.i386.rpm
- connect("username","passwd","tns"),只要tnsping的通就行了
- 向oracle多个表定时插入数据
- import cx_Oracle
- import random
- import itertools
- import string
- import time
- conn = cx_Oracle.connect("irene","password","127.0.0.1:1521/scutech")
- cursor = conn.cursor()
- #sql1 = "create table customer(id number(5),name varchar2(30),addr varchar2(50),tel number(20),comp varchar2(50),year number(2))"
- #sql11 = "create table goods(id number(5),name varchar2(30),addr varchar2(50),numb number(20),reserve number(10),price number(10))"
- #sql12 = "create table sponsor(id number(5),name varchar2(30),tel number(20),goods varchar2(50),price number(10))"
- #sql13 = "create table restaurant(id number(5),name varchar2(30),price number(10),addr varchar2(50),le number(2))"
- #sql14 = "create table performance(id number(5),name varchar2(30),salary number(10),goods varchar2(50),perfo varchar(2),year number(2))"
- #sql15 = "create table financial(id number(5),inside number(10),outside number(10),goods varchar2(50),people varchar2(30))"
- #sql16 = "create table property(id number(5),name varchar2(30),price number(10),people varchar2(30),inpeople varchar2(30))"
- #cursor.execute(sql1)
- #cursor.execute(sql11)
- #cursor.execute(sql12)
- #cursor.execute(sql13)
- #cursor.execute(sql14)
- #cursor.execute(sql15)
- #cursor.execute(sql16)
- i=0
- str1 = 'abcdefghijklmnopqrstuvwxyz1234567890'
- var = 'abcdefghijklmnopqrstuvwxyz'
- nn = [1,2,3,4,5,6,7,8,9,0]
- while i<3:
- n1 = random.randint(0,15)
- n2 = random.randint(16,25)
- # 10 random.randint(9999999,999999999)
- # 20 random.randint(9999999999,9999999999999)
- # 2 random.randint(0,50)
- name = "".join(itertools.chain(*random.sample(str1,n1)))
- addr = "".join(itertools.chain(*random.sample(str1,n2)))
- comp = "".join(itertools.chain(*random.sample(var,n2)))
- goods = "".join(itertools.chain(*random.sample(str1,n2)))
- people = "".join(itertools.chain(*random.sample(str1,n1)))
- inpeople = "".join(itertools.chain(*random.sample(str1,n1)))
- #***************************************************************customer***********************************************************
- param_c={'id':i,'name':name,'addr':addr,'tel':random.randint(999999999,999999999999),'comp':comp,'year':random.randint(0,50)}
- ww = 'insert into customer values($id,\'$name\',\'$addr\',$tel,\'$comp\',$year)'
- pp = string.Template(ww)
- sql2 = pp.substitute(param_c)
- # print sql2
- cursor.execute(sql2)
- #***************************************************************goods***************************************************************
- #param_g={'id':i,'name':name,'addr':addr,'numb':20,'reserve':10,'price':10}
- param_g={'id':i,'name':name,'addr':addr,'numb':random.randint(9999999999,9999999999999),'reserve':random.randint(9999999,999999999),'price':random.randint(9999999,999999999)}
- ww1 = 'insert into goods values($id,\'$name\',\'$addr\',$numb,$reserve,$price)'
- pp1 = string.Template(ww1)
- sql21 = pp1.substitute(param_g)
- # print sql21
- cursor.execute(sql21)
- #***************************************************************sponsor*************************************************************
- #param_s={'id':i,'name':name,'tel':20,'price':10,'goods':goods}
- param_s={'id':i,'name':name,'tel':random.randint(9999999999,999999999999),'price':random.randint(9999999,999999999),'goods':goods}
- ww2 = 'insert into sponsor values($id,\'$name\',$tel,\'$goods\',$price)'
- pp2 = string.Template(ww2)
- sql22 = pp2.substitute(param_s)
- # print sql22
- cursor.execute(sql22)
- #***************************************************************restaurant**********************************************************
- #param_r={'id':i,'name':name,'price':10,'addr':addr,'level':2}
- param_r={'id':i,'name':name,'price':random.randint(9999999,999999999),'addr':addr,'level':random.randint(0,50)}
- ww3 = 'insert into restaurant values($id,\'$name\',$price,\'$addr\',$level)'
- pp3 = string.Template(ww3)
- sql23 = pp3.substitute(param_r)
- # print sql23
- cursor.execute(sql23)
- #***************************************************************performance*********************************************************
- #param_pe={'id':i,'name':name,'salary':10,'goods':goods,'perfo':2,'year':2}
- param_pe={'id':i,'name':name,'salary':random.randint(9999999,999999999),'goods':goods,'perfo':random.randint(0,50),'year':random.randint(0,50)}
- ww4 = 'insert into performance values($id,\'$name\',$salary,\'$goods\',$perfo,$year)'
- pp4 = string.Template(ww4)
- sql24 = pp4.substitute(param_pe)
- # print sql24
- cursor.execute(sql24)
- #***************************************************************financial***********************************************************
- #param_f={'id':i,'outside':10,'inside':10,'goods':goods,'people':people}
- param_f={'id':i,'outside':random.randint(9999999,999999999),'inside':random.randint(9999999,999999999),'goods':goods,'people':people}
- ww5 = 'insert into financial values($id,$outside,$inside,\'$goods\',\'$people\')'
- pp5 = string.Template(ww5)
- sql25 = pp5.substitute(param_f)
- # print sql25
- cursor.execute(sql25)
- #***************************************************************property************************************************************
- #param_pr={'id':i,'name':name,'price':10,'people':people,'inpeople':inpeople}
- param_pr={'id':i,'name':name,'price':random.randint(9999999,999999999),'people':people,'inpeople':inpeople}
- ww6 = 'insert into property values($id,\'$name\',$price,\'$people\',\'$inpeople\')'
- pp6 = string.Template(ww6)
- sql26 = pp6.substitute(param_pr)
- # print sql26
- cursor.execute(sql26)
- print i
- i += 1
- time.sleep(30)
- conn.commit()
- cursor.close()
- conn.close()
- 写文件输出文件初体验
- fobj=open('test','w')
- fobj.write('hello world')
- fobj.close()
- python+splinter+iframe初体验
- import time
- from splinter import Browser
- browser = Browser()
- browser.visit('**********************')
- time.sleep(3)
- if browser.find_by_id('lhgfrm_lhgdgId'):
- with browser.get_iframe('lhgfrm_lhgdgId') as frame:
- frame.find_by_id('trialRadio').click()
- frame.find_by_id('continue').click()
- browser.fill('username','admin')
- browser.fill('password','admin')
- browser.find_by_name('Submit').click()
- time.sleep(8)
- na = browser.find_by_id('Navigate5')
- na.click()
- na.find_by_tag('a')[2].click()
- time.sleep(3)
- browser.fill('strFTPName','python')
- browser.find_by_id('hostInput').find_by_tag('input').fill('192.168.88.183')
- browser.fill('textfield','python')
- browser.find_by_id('Submit').click()
- time.sleep(3)
- alter = browser.get_alert()##这两句的意思是处理弹出框
- alter.accept()
- time.sleep(3)
- browser.quit()
- 处理html页面元素实例
- #-*-coding=utf-8
- import time
- from splinter import Browser
- file1 = open('/home/irene/Documents/python/userpasswd')#打开userpasswd文件
- i=0
- while i < 50:
- browser = Browser()
- browser.visit('**************************')#访问页面
- m = file1.readline()#逐行读取文件
- uname = m[10:len(m)-1]#截取字符串
- print uname
- browser.fill('username',uname)#向页面输入文字
- m = file1.readline()
- passwd = m[8:len(m)-1]
- print passwd
- browser.fill('password',passwd)
- browser.find_by_name('Submit').click()#单击按钮
- i +=1
- assert browser.is_element_present_by_id('treeNodeId1')
- browser.find_link_by_href('javascript:void(0)')[1].click()
- browser.find_link_by_text('进入').click()
- browser.find_link_by_href('BackupWizardOracle.php?type=1').click()
- browser.find_by_tag('button')[0].click()#备份资源类型
- browser.find_by_tag('button')[3].click()#备份方法
- browser.find_by_tag('input')[24].click()#选择存储服务
- browser.find_by_tag('button')[6].click()#设备
- browser.find_by_tag('input')[29].click()#设置作业执行时间
- ti = browser.find_by_id('hour')
- ti.find_by_xpath("//option[@value='16']").click()
- browser.find_by_tag('button')[9].click()#作业信息
- alert = browser.get_alert()#处理弹出框
- alert.accept()
- browser.find_by_tag('button')[12].click()#提交作业
- browser.quit()
- file1.close()
- 批量增加用户
- import time
- import random
- import itertools
- from splinter import Browser
- browser = Browser()
- browser.visit('*********************')
- time.sleep(3)
- browser.fill('username','admin')
- browser.fill('password','admin')
- browser.find_by_name('Submit').click()
- time.sleep(3)
- str1 = 'abcdefghijklmnopqrstuvwxwy0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
- fobj = open('/home/irene/Documents/python/userpasswd','w')
- i=0
- while i<200:
- na = browser.find_by_id('Navigate1')
- na.click()
- na.find_by_tag('a')[2].click()
- time.sleep(3)
- nu = random.randint(5,16)
- np = random.randint(10,29)
- name = "".join(itertools.chain(*random.sample(str1,nu)))
- passwd = "".join(itertools.chain(*random.sample(str1,np)))+str(i)
- browser.fill('username',name)
- browser.fill('password',passwd)
- browser.fill('confirmpassword',passwd)
- browser.fill('email','3r543@se.com')
- browser.find_by_id('telephone').fill(passwd)
- browser.find_by_id('RegisterBut').click()
- time.sleep(3)
- alert = browser.get_alert()
- alert.accept()
- i +=1
- print i
- fobj.write('username: '+name+'\n')
- fobj.write('passwd: '+passwd+'\n')
- time.sleep(30)
- fobj.close()
- browser.quit()
- 函数初体验
- #-*-coding=utf-8
- import time
- from splinter import Browser
- browser = Browser()
- browser.visit('http://192.168.88.185/dbackup')#访问页面
- browser.fill('username','dingjia')#向页面输入文字
- browser.fill('password','dingjia123')
- browser.find_by_name('Submit').click()#单击按钮
- assert browser.is_element_present_by_id('treeNodeId1')
- browser.find_link_by_href('javascript:void(0)')[1].click()
- browser.find_link_by_text('进入').click()
- #dlog是否删除归档日志
- def fun(type,method,equipment,jobname,dlog):
- browser.find_link_by_href('BackupWizardOracle.php?type=1').click()
- time.sleep(3)
- #备份资源类型
- print type
- browser.find_by_id(type).click()
- time.sleep(4)
- #是否备份表空间
- if(type=='tablespaceRadio'):
- browser.find_by_id('tablespaceChecbox').click()
- time.sleep(2)
- #是否备份数据文件
- if(type=='datafileRadio'):
- browser.find_by_id('datafileChecbox').click()
- time.sleep(2)
- #是否删除归档日志
- if(dlog=='n'):
- browser.find_by_id('archivedlogCheckbox').click()
- time.sleep(2)
- browser.find_by_tag('button')[0].click()#下一步
- #备份方法
- browser.find_by_id(method).click()
- browser.find_by_tag('button')[3].click()#下一步
- time.sleep(5)
- #设备
- browser.find_by_id(equipment).click()
- browser.find_by_tag('button')[6].click()#下一步
- time.sleep(2)
- #作业信息
- browser.find_by_id('jobName').fill(jobname)
- browser.find_by_tag('button')[9].click()#下一步
- time.sleep(2)
- #作业摘要
- browser.find_by_tag('button')[12].click()#提交作业
- time.sleep(5)
- if __name__ == "__main__":
- #---------------------数据库---------------------
- print '数据库(删除归档)--完全备份--本地'
- fun('databaseRadio','fullRadio','diskRadio','DFD0','')
- print '数据库(删除归档)--差异增量备份--本地'
- fun('databaseRadio','differenceRadio','diskRadio','DDD1','')
- print '数据库(删除归档)--累积增量增量备份--本地'
- fun('databaseRadio','accumulationRadio','diskRadio','DAD1','')
- print '数据库(删除归档)--完全备份--存储服务器'
- fun('databaseRadio','fullRadio','ftpRadio','DFF1','')
- print '数据库(删除归档)--差异增量备份--存储服务器'
- fun('databaseRadio','differenceRadio','ftpRadio','DDF1','')
- print '数据库(删除归档)--累积增量增量备份--存储服务器'
- fun('databaseRadio','accumulationRadio','ftpRadio','DAF1','')
- print '数据库(不删除归档)--完全备份--本地'
- fun('databaseRadio','fullRadio','diskRadio','DFDn','n')
- print '数据库(不删除归档)--差异增量备份--本地'
- fun('databaseRadio','differenceRadio','diskRadio','DDDn','n')
- print '数据库(不删除归档)--累积增量增量备份--本地'
- fun('databaseRadio','accumulationRadio','diskRadio','DADn','n')
- print '数据库(不删除归档)--完全备份--存储服务器'
- fun('databaseRadio','fullRadio','ftpRadio','DFFn','n')
- print '数据库(不删除归档)--差异增量备份--存储服务器'
- fun('databaseRadio','differenceRadio','ftpRadio','DDFn','n')
- print '数据库(不删除归档)--累积增量增量备份--存储服务器'
- fun('databaseRadio','accumulationRadio','ftpRadio','DAFn','n')
- #---------------------表空间-----------------------
- print '表空间(删除归档)--完全备份--本地'
- fun('tablespaceRadio','fullRadio','diskRadio','TFD1','')
- print '表空间(删除归档)--差异增量备份--本地'
- fun('tablespaceRadio','differenceRadio','diskRadio','TDD1','')
- print '表空间(删除归档)--累积增量增量备份--本地'
- fun('tablespaceRadio','accumulationRadio','diskRadio','TAD1','')
- print '表空间(删除归档)--完全备份--存储服务器'
- fun('tablespaceRadio','fullRadio','ftpRadio','TFF1','')
- print '表空间(删除归档)--差异增量备份--存储服务器'
- fun('tablespaceRadio','differenceRadio','ftpRadio','TDF1','')
- print '表空间(删除归档)--累积增量增量备份--存储服务器'
- fun('tablespaceRadio','accumulationRadio','ftpRadio','TAF1','')
- print '表空间(不删除归档)--完全备份--本地'
- fun('tablespaceRadio','fullRadio','diskRadio','TFDn','n')
- print '表空间(不删除归档)--差异增量备份--本地'
- fun('tablespaceRadio','differenceRadio','diskRadio','TDDn','n')
- print '表空间(不删除归档)--累积增量增量备份--本地'
- fun('tablespaceRadio','accumulationRadio','diskRadio','TDAn','n')
- print '表空间(不删除归档)--完全备份--存储服务器'
- fun('tablespaceRadio','fullRadio','ftpRadio','TFFn','n')
- print '表空间(不删除归档)--差异增量备份--存储服务器'
- fun('tablespaceRadio','differenceRadio','ftpRadio','TDFn','n')
- print '表空间(不删除归档)--累积增量增量备份--存储服务器'
- fun('tablespaceRadio','accumulationRadio','ftpRadio','TAFn','n')
- #---------------------数据文件---------------------
- print '数据文件(删除归档)--完全备份--本地'
- fun('datafileRadio','fullRadio','diskRadio','DFFD1','')
- print '数据文件(删除归档)--差异增量备份--本地'
- fun('datafileRadio','differenceRadio','diskRadio','DFDD1','')
- print '数据文件(删除归档)--累积增量增量备份--本地'
- fun('datafileRadio','accumulationRadio','diskRadio','DFAD1','')
- print '数据文件(删除归档)--完全备份--存储服务器'
- fun('datafileRadio','fullRadio','ftpRadio','DFFF1','')
- print '数据文件(删除归档)--差异增量备份--存储服务器'
- fun('datafileRadio','differenceRadio','ftpRadio','DFDF1','')
- print '数据文件(删除归档)--累积增量增量备份--存储服务器'
- fun('datafileRadio','accumulationRadio','ftpRadio','DFAF1','')
- print '数据文件(不删除归档)--完全备份--本地'
- fun('datafileRadio','fullRadio','diskRadio','DFFDn','n')
- print '数据文件(不删除归档)--差异增量备份--本地'
- fun('datafileRadio','differenceRadio','diskRadio','DFDDn','n')
- print '数据文件(不删除归档)--累积增量增量备份--本地'
- fun('datafileRadio','accumulationRadio','diskRadio','DFADn','n')
- print '数据文件(不删除归档)--完全备份--存储服务器'
- fun('datafileRadio','fullRadio','ftpRadio','DFFFn','n')
- print '数据文件(不删除归档)--差异增量备份--存储服务器'
- fun('datafileRadio','differenceRadio','ftpRadio','DFDFn','n')
- print '数据文件(不删除归档)--累积增量增量备份--存储服务器'
- fun('datafileRadio','accumulationRadio','ftpRadio','DFAFn','n')
- #---------------------归档日志---------------------
- print '归档日志(删除归档)--差异增量备份--本地'
- fun('archivedlogRadio','differenceRadio','diskRadio','ADD1','')
- print '归档日志(删除归档)--差异增量备份--存储服务器'
- fun('archivedlogRadio','differenceRadio','ftpRadio','ADF1','')
- print '归档日志(不删除归档)--差异增量备份--本地'
- fun('archivedlogRadio','differenceRadio','diskRadio','ADDn','n')
- print '归档日志(不删除归档)--差异增量备份--存储服务器'
- fun('archivedlogRadio','differenceRadio','ftpRadio','ADFn','n')
- browser.quit()
- python+HTMLParser+urllib
- from HTMLParser import HTMLParser
- from htmlentitydefs import name2codepoint
- import urllib
- class MyHTMLParser(HTMLParser):
- def handle_starttag(self,tag,attrs):
- print "Start tag:",tag
- for attr in attrs:
- print " attr:",attr
- def handle_endtag(self,tag):
- print "End tag:",tag
- def handle_data(self,data):
- print "Data :",data
- def handle_comment(self,data):
- print "Comment :",data
- def handle_entityref(self,name):
- c = unichr(name2codepoint[name])
- print "Named ent:",c
- def handle_decl(self,data):
- print "Decl :",data
- parser = MyHTMLParser()
- #parser local web html page
- #parser.feed(open("/home/scutech/python/webpage/hello.html").read())
- #parser online web html page
- page = urllib.urlopen('http://localhost/dbackup/UnitManage/UnitMainPage.php')
- da = page.read(page)
- parser.feed(da)
- 在AIX上安装rpm包
- import subprocess
- import time
- filename = '/home/shuixian/dbackup-agent-2.2-8722.15.aix5.1.ppc.rpm'
- order = 'sudo rpm -ivh '+filename
- p = subprocess.call(order,shell=True)
- time.sleep(10)
- pp = subprocess.Popen('sudo /usr/sbin/dbackup_agentd config',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- print '0'
- pp.stdin.write('oracle'+'\n')
- print '1'
- time.sleep(2)
- pp.stdin.write('/opt/oracle/product/9.2.0.1.0'+'\n')
- print '2'
- time.sleep(2)
- pp.stdin.write('Y'+'\n')
- print '3'
- time.sleep(2)
- pp.stdin.write('192.168.88.184'+'\n')
- print '4'
- time.sleep(2)
- pp.stdin.write('443'+'\n')
- print '5'
- time.sleep(2)
- pp.stdin.write('Y'+'\n')
- print '6'
- time.sleep(7)
- 在AIX上下载升级rpm包
- from ftplib import FTP
- import subprocess
- #********************************ftp上的最新版本*************************
- ftp=FTP('192.168.88.10')
- ftp.login('******','******')
- path='ftp_product_installer/wddps/2013/2.2.15'
- ftp.cwd(path)
- data=[]
- k = []
- fobj=open('/home/shuixian/write','w')
- ftp.retrlines('LIST')
- for name in ftp.nlst():
- data.append(name)
- for m in range(len(data)):
- a = '.15.aix5.1.ppc.rpm'
- b = data[m].find(a)
- if b > 0:
- k.append(data[m])
- lastest = k[-1][0:25]
- #********************************本机所安装的版本************************
- proc=subprocess.Popen('rpm -qa|grep dbackup-agent',shell=True,stdout=subprocess.PIPE)
- out,err=proc.communicate()
- newest=out[0:-1]
- #********************************比较两个版本***************************
- c = cmp(newest,lastest)
- Download='/home/shuixian/'+k[-1]
- f = open(Download,'wb')
- #********************************小于0则需要下载升级,大于0则不需要*********
- if c < 0:
- ftp.retrbinary('RETR '+k[-1],f.write,1024)
- f.close()
- #********************************关闭ftp******************************
- ftp.quit()
- #********************************升级dbackup-agent********************
- order = ‘sudo rpm -Uvh '+Download
- pp = subprocess.call(order,shell=True)
- 整合16、17
- import subprocess
- import time
- from ftplib import FTP
- def install(filename,order_i,config,ora_home,ip):
- order = order_i + filename
- p = subprocess.call(order,shell=True)
- time.sleep(10)
- pp = subprocess.Popen(config,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- pp.stdin.write('oracle'+'\n')
- time.sleep(2)
- pp.stdin.write(ora_home + '\n')
- time.sleep(2)
- pp.stdin.write('Y'+'\n')
- time.sleep(2)
- pp.stdin.write(ip+'\n')
- time.sleep(2)
- pp.stdin.write('443'+'\n')
- time.sleep(2)
- pp.stdin.write('Y'+'\n')
- time.sleep(7)
- print 'Dbackup-agent's installation successful'
- def upgrade(path,suffix,download,order_u,order_s):
- ftp=FTP('192.168.88.10')
- ftp.login('scutech','dingjia')
- ftp.cwd(path)
- data=[]
- k=[]
- for name in ftp.nlst():
- data.append(name)
- for m in range(len(data)):
- b = data[m].find(suffix)
- if b > 0:
- k.append(data[m])
- lastest=k[-1][0:len(k[-1])-len(suffix)-3]
- proc=subprocess.Popen(order_s,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- out,err=proc.communicate()
- newest=out[0:-1]
- c=cmp(newest,lastest)
- f = open(download + k[-1],'wb')
- if c < 0:
- ftp.retrbinary('RETR '+k[-1],f.write,1024)
- f.close()
- ftp.quit()
- pp = subprocess.call(order_u,shell=True)
- print 'Dbackup-agent upgrade success'
- if __name__=="__main__":
- filename = '/home/shuixian/dbackup-agent-2.2-8722.15.aix5.1.ppc.rpm'
- order_i = 'sudo rpm -ivh '
- order_u = 'sudo rpm -Uvh '
- order_s = 'rpm -qa|grep dbackup-agent'
- config = 'sudo /usr/sbin/dbackup_agentd config'
- ora_home = '/opt/oracle/product/9.2.0.1.0'
- ip = '192.168.88.10'
- path = 'ftp_product_installer/wddps/2013/2.2.15'
- suffix = '.15.aix5.1.ppc.rpm'
- download = '/home/shuixian/'
- a = subprocess.call(order_s,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- out,err=a.communicate()
- if len(out)>0:
- upgrade(path,suffix,download,order_u,order_s)
- else:
- install(filename,order_i,config,ora_home,ip)
- 改良17
- from ftplib import FTP
- import re
- ftp = FTP('192.168.1.104')
- ftp.login('scutech','dingjia')
- path = '/home/scutech/Downloads'
- ftp.cwd(path)
- data = []
- filename = ''
- for name in ftp.nlst():
- f = 'dbackup-server-2\.2-....\.15_all\.deb'
- res = re.search(f,name)
- if res !=None:
- filename = name
- print filename
- ftp.quit()
- 杂
- import os,time
- import subprocess
- time2sleep = 2.5
- fobj=open('/tmp/shuixian/write','w')
- while True:
- print int(time.time())
- proc=subprocess.Popen('top 0',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- out,err=proc.communicate()
- fobj.write(out)
- time.sleep(time2sleep)
- fobj.close()
- import os,time
- fobj=open('/tmp/shuixian/write','w')
- time2sleep = 2.5
- while True:
- print int(time.time())
- out=os.popen('top -bi -n 2 -d 0.02').read()
- fobj.write(out)
- print os.popen('top -bi -n 2 -d 0.02').read().split('\n\n\n')[0].split('\n')
- time.sleep(time2sleep)
- out = os.popen('top|head -12').read().split('\n\n\n')[0].split('\n')
- tmp11=out[11]
- tmp10 = out[10]
- tmp9 = out[9]
- tmp8 = out[8]
- tmp7 = out[7]
- tmp6 = out[6]
- tmp5 = out[5]
- tmp10=re.search('....%',out[10]).group()
- import os,time,re
- fobj=open('/tmp/shuixian/write','w')
- i=0
- while i<38:
- print '***************************************'
- print i
- out = os.popen('top|head -12').read().split('\n\n\n')[0].split('\n')
- llen = len(out)
- tmp = 0
- k = 0
- while k <5:
- name = re.search('....%',out[llen-k-2]).group()
- tmp = float(tmp)+float(name[:-1])
- print tmp
- k +=1
- i +=1
- print tmp
- mem = re.search('....M f',out[3]).group()[:-2]
- shijian = re.search('........$',out[0]).group()
- cpu = str(tmp)
- result =cpu+' '+mem+' '+shijian
- fobj.write(result)
- fobj.write('\n')
- time.sleep(5)
- fobj.close()
- import os,time,re
- fobj=open('/tmp/shuixian/write','w')
- i=0
- while i<38:
- print '***************************************'
- print i
- out = os.popen('top|head -12').read().split('\n\n\n')[0].split('\n')
- print out[6]
- time.sleep(5)
- fobj.close()
- time.strftime('%H:%M:%S',time.localtime(time.time()))
- import time,subprocess
- ttime = time.strftime('%H:%M:%S',time.localtime(time.time()))
- print ttime
- fobj=open('/tmp/shuixian/write','w')
- i = 2
- h=float(ttime[:2])
- m=float(ttime[-5:-3])
- s=float(ttime[-2:])
- p=subprocess.Popen('vmstat 3 45',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- out,err=p.communicate()
- print out
- print '*******************************************************'
- while i < 29:
- tmp=out.split('\n')[i].split(' ')
- ll = len(tmp)
- if tmp[ll-2] !='':
- mem = tmp[5]
- us = tmp[ll-3]
- sy = tmp[ll-2]
- else:
- mem= tmp[5]
- us = tmp[ll-4]
- sy = tmp[ll-3]
- c = cmp(s,60)
- if c == 1:
- s = 0
- m +=1
- mm = str(m)
- ss = str(s)
- if m<10:
- mm = '0' + str(m)[0]
- else:
- mm = str(m)[:2]
- if s<10:
- ss = '0' + str(s)[0]
- else:
- ss = str(ss)[:2]
- s +=3
- i +=1
- tttime = str(h)[:2]+':'+mm+':'+ss
- print tttime
- result = us+' '+sy+' '+mem+' '+tttime+'\n'
- print result
- fobj.write(result)
- fobj.close()
- 获取cpu_mem等
- import subprocess,time
- fobj=open('/home/tingkai/shuixian/write','w')
- fobj1=open('/home/tingkai/shuixian/us.txt','w')
- fobj2=open('/home/tingkai/shuixian/sy.txt','w')
- fobj3=open('/home/tingkai/shuixian/mem.txt','w')
- fobj4=open('/home/tingkai/shuixian/time.txt','w')
- ttime = time.strftime('%H:%M:%S',time.localtime(time.time()))
- p=subprocess.Popen('vmstat 1 1200',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- out=p.communicate()
- mem = 'echo \"'+out[0] + " \"| awk '{print $5}'"
- us = 'echo \"'+out[0] + " \"| awk '{print $16}'"
- sy = 'echo \"'+out[0] + " \"| awk '{print $17}'"
- p1=subprocess.Popen(us,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- p2=subprocess.Popen(sy,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- p3=subprocess.Popen(mem,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- pp1=p1.communicate()
- pp2=p2.communicate()
- pp3=p3.communicate()
- i=2
- h=float(ttime[:2])
- m=float(ttime[-5:-3])
- s=float(ttime[-2:])
- while i < 1266:
- c1=cmp(m,60)
- c2=cmp(s,60)
- if c2 == 1:
- s=0
- m +=1
- if c1 == 1:
- m=0
- h +=1
- fobj4.write(str(int(h))+':'+str(int(m))+':'+str(int(s))+'\n')
- i +=1
- s +=1
- fobj.write(out[0]+'\n')
- fobj1.write(pp1[0])
- fobj2.write(pp2[0])
- fobj3.write(pp3[0])
- fobj.close()
- fobj1.close()
- fobj2.close()
- fobj3.close()
- fobj4.close()
- 自定义类的调用
自定义类:(路径:/home/irene/Documents/python/Class/Circle.py)- import math
- class Circle:
- #Construct a circle object
- def __init__(self,radius = 1):
- self.radius = radius
- def getPerimeter(self):
- return 2 * self.radius * math.pi
- def getArea(self):
- return self.radius * self.radius * math.pi
- def setRadius(self,radius):
- self.radius=radius
- import sys
- sys.path.append(r'/home/irene/Documents/python/Class')
- from Circle import Circle
- import time
- print(time.strftime('%H:%M:%S',time.localtime(time.time())))
- c = Circle(5)
- print("Radius:",c.radius)
- print("Perimeter:",c.getPerimeter())
- print("Area:",c.getArea())
结果:
- 09:54:55
- ('Radius:', 5)
- ('Perimeter:', 31.41592653589793)
- ('Area:', 78.53981633974483)
- ubuntu12.10+python2.7安装cx_Oracle和oracle的客户端
oracle-client
下载oracle客户端:http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
我下载的是:oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm
将rpm包装为deb包:sudo alien oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm
安装:sudo dpkg -i oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm
安装之后的默认目录:/usr/lib/oracle/11.2/client64
添加oracle的环境变量:
export ORACLE_HOME=/usr/lib/oracle/11.2/client64
export PATH=$PATH:$ORACLE_HOME/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib
export TNS_ADMIN=$ORACLE_HOME/network/admin
source ~/.profile
创建tnsnames.ora目录并添加编辑该文件:sudo mkdir -p /usr/lib/oracle/11.2/client64/network/admin
内容:
ORACLE=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.88.196)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = oracle10g)
)
)
cx_Oracle
下载cx_Oracle:http://sourceforge.net/projects/cx-oracle/files/5.1.2/cx_Oracle-5.1.2-11g-py27-1.x86_64.rpm
下载之后解压,在当前目录下发现一个usr文件夹,将此文件夹下的cx_Oracle.so拷贝到/usr/local/lib/python2.7/dist-packages
cp /home/irene/Downloads/usr/lib/python2.7/site-packages/cx_Oracle.so /usr/local/lib/python2.7/dist-packages/
实践:
python
>>import cx_Oracle
>>conn = conn("system/password@192.168.88.196:1521@oracle10g")
大功告成!!
借鉴:http://linux.chinaitlab.com/set/890093.html - shell+python实现oracle自动导出
- exp.sh
- cmd='exp scott/dingjia@ora10g tables=one file=/home/oracle/Desktop/backup/one.dmp'
- log_file='/home/oracle/Desktop/backup/exp.log'
- echo $cmd>>$log_file
- `$cmd`
- sleep 10
- exp.py
- import subprocess,time
- order = '/home/oracle/Desktop/backup.exp.sh'
- i = 0
- while i<5:
- p = subprocess.Popen(order,shell=True)
- print '============'+str(i)+'=========='
- i += 1
- time.sleep(60)
- Date格式化输出
- [root@root ~]# date "+%Y-%m-%d"
- 2013-02-19
- [root@root ~]# date "+%H:%M:%S"
- 13:13:59
- [root@root ~]# date "+%Y-%m-%d %H:%M:%S"
- 2013-02-19 13:14:19
- [root@root ~]# date "+%Y_%m_%d %H:%M:%S"
- 2013_02_19 13:14:58
- [root@root ~]# date -d today
- Tue Feb 19 13:10:38 CST 2013
- [root@root ~]# date -d now
- Tue Feb 19 13:10:43 CST 2013
- [root@root ~]# date -d tomorrow
- Wed Feb 20 13:11:06 CST 2013
- [root@root ~]# date -d yesterday
- Mon Feb 18 13:11:58 CST 2013