1. 程式人生 > >python錯誤和異常,re模塊,多線程,paramiko模塊

python錯誤和異常,re模塊,多線程,paramiko模塊

pin 循環列表 use 可能 一起 down get mman tom

文件操作
x=open(‘/etc/hosts‘) ###默認讀的方式打開
x.readline()
x.read()
x.seek(0)
y=open(‘/root/new.txt‘,‘w‘)
y.writelines(‘abcd\n‘)
y.flush() 保存
y.close()

函數
def 函數名(x,y=11):
命令

函數名(‘tom‘,‘jerry‘)

NameErrot 未聲明錯誤
IndexError 沒有索引
SyntaxError 語法錯誤
KeyboardInterrupt 用戶按ctrl+c(中斷)錯誤
EOFError ctrl+d錯誤

IOErrot 輸入/輸出操作失敗
ZeroDivisionError 整數整除錯誤(如 3/0 錯誤)
ValueError 值錯誤 (如 字符串不是整數)
###############################
設定錯誤提示 ##可以把多個excep語句連接在一起,處理一個try塊中可能發生的多種異常
#!/usr/bin/python
#coding:utf-8
try:
raw_input(‘請輸入用戶名:‘)
except KeyboardInterrupt: ##如果上面結果出現異常KeyboardInterrupt(ctrl+c)錯誤 就打印ctrl+c
print ‘\n你按了ctrl+c‘
except EOFError: ##如果上面結果出現異常EOFError錯誤 就打印ctrl+d
print ‘\n你按了ctrl+d‘
except: ##如果上面結果出現其他異常錯誤 就打印你出錯了
print ‘出錯了‘
#################################
數字錯誤
#!/usr/bin/python
#coding:utf-8
try:
x=int(raw_input(‘請輸入數字:‘))
print 3/x
except ZeroDivisionError:
print ‘不能輸入0‘
except ValueError:
print ‘你輸入的不是數字‘
#################################
把錯誤內容賦給變量
#!/usr/bin/python
#coding:utf-8
try:
x=int(raw_input(‘請輸入數字:‘))
print 3/x
except ZeroDivisionError,e:
print ‘你錯了‘,e
except ValueError:
print ‘你輸入的不是數字‘

###################################
#!/usr/bin/python
#coding:utf-8
try:
x=int(raw_input(‘請輸入數字:‘)) ##輸入字符串,轉化為整數,再賦值給x
print 3/x
except ZeroDivisionError,e:
print ‘你錯了‘,e
except ValueError:
print ‘你輸入的不是數字‘
else:
print ‘沒毛病‘ ##不出錯執行
finally:
print ‘Game Over‘ ##出不出錯都執行
#######################################
確定文件有沒有關

>> x=open(‘/etc/hosts‘)
>> x.closed ##文件關閉了嗎
False
>> x.close() ##關閉文件
>> x.closed
True
##################################
>> with open(‘/etc/hosts‘) as x: ##將打開的文件操作放在with語句中的x內,代碼結局後,沒有縮進,文件自動關閉
... x.readline() ##讀一行包含結束符號\n
... x.readline() ##讀一行包含結束符號\n
... ##沒有縮進代表結束
‘127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4\n‘ ##文件第一行
‘::1 localhost localhost.localdomain localhost6 localhost6.localdomain6\n‘ ##文件第二行
>> x.closed ##文件關閉了嗎
True ##關閉

#################################
條件判斷命令的結果
#!/usr/bin/python
#coding:utf-8
x=int(raw_input(‘請輸入1-100數字:‘))
try:
if x>100:
raise ValueError,‘值不能大於100‘ ##把x的結果觸發為異常ValueError
if x<1:
raise ValueError,‘值不能小於1‘
except ValueError,e: ##如果異常出現ValueError,把內容給e
print e ##打印錯誤顯示的內容

########################################
re模塊
################################

>> import re
re.match正則匹配,僅匹配開頭^
>> x=re.match(‘hello‘,‘hello the world‘)
>> x.group()
‘hello‘

>> import re
re.search正則匹配,匹配全部位置,僅匹配第一個
x=re.search(‘the‘,‘hello the wod,,he app‘)
>> x.group()
‘the‘

>> import re
re.findall正則匹配,匹配全部位置,全部內容
>> x=re.findall(‘the‘,‘hello the wod,,the app‘)
>> x
[‘the‘, ‘the‘]

>> import re
>> m=re.finditer(‘foo‘,‘seafood is food‘)
>> for item in m:
... print item.group()
...
foo
foo

>> patt=re.compile(‘foo‘) ##把foo編譯成二進制,傳給patt
>> m=patt.match(‘food‘) ##在food內容中匹配到foo,傳給m
>> print m.group() ##顯示m的內容
foo

>> mylist=re.split(‘.|-‘,‘hello-world.data‘) ##使用.或者-為分隔符,把字符串分為一個列表,把結果給mylist
>> print mylist
[‘hello‘, ‘world‘, ‘data‘]

>> m=re.sub(‘X‘,‘Mr.smith‘,‘attn:X\nDearX‘) ##把X替換成Mr.smith
>> print m
attn:Mr.smith
DearMr.smith

###################################################
用awk統計日誌內容中ip個數
awk ‘{IP[$1]++} END{for(i in IP){print i,IP[i]}}‘ 每個ip訪問次數

###################################################
統計用firefox和curl瀏覽器訪問的數量
#!/usr/bin/python
#coding:utf-8
import re
z=0
file1=open(‘/var/log/httpd/access_log‘)
for i in file1:
x=re.search(‘Firefox‘,i)
if x:
z+=1
file1.close()
print ‘用Firefox的數量是%d‘ %z
g=0
file2=open(‘/var/log/httpd/access_log‘)
for i in file2:
x=re.search(‘curl‘,i)
if x:
g+=1
file2.close()
print ‘用curl的數量是%d‘ %g
#################################
相對上個腳本簡單一些 字典{‘下標‘:值,‘下標‘:值,.....} dic.get(key,0) 下標有key就取key(下標)的值,沒有就取0
#!/usr/bin/python
#coding:utf-8
import re
dic={} ###為字典
data=open(‘/var/log/httpd/access_log‘)
for i in data:
m = re.search(‘(Firefox|curl)‘,i) ##把匹配的內容給m
if m: ##如果m存在,就繼續下面
key=m.group() ###取出m的內容,變成key
dic[key]=dic.get(key,0)+1 ###累加dic字典下標firefox的值
print dic
###########################################
python 自動ping主及
#!/usr/bin/python
#coding:utf-8
import subprocess
def myping(x):
m=subprocess.call(‘ping -c2 -i0.5 -W2 W%s &>/dev/null‘%x,shell=True)
if m==0:
print ‘%s is up‘ %x
else:
print ‘%s is down‘ %x
ip=[‘176.121.205.%s‘%i for i in xrange(1,100)] ##定義列表並賦值
for j in ip: ###循環列表
myping(j)
#################################################
多進程 [每個進程,都有自己的內存]
多線程 [共享一塊內存]

多線程ping主機比上面快
#!/usr/bin/python
#coding:utf-8
import threading
import subprocess
def myping(x):
m=subprocess.call(‘ping -c2 %s &>/dev/null‘%x,shell=True)
if m==0:
print ‘%s is up‘ %x
else:
print ‘%s is down‘ %x
ip=[‘176.121.205.%s‘%i for i in xrange(1,254)]
for j in ip:
a=threading.Thread(target=myping,args=[j])
a.start()
#################################################
利用多線程遠程主機,執行命令
#!/usr/bin/python
#coding:utf-8
import paramiko
import threading
def myssh(x): ##定義函數
host = x ##遠程的主機ip
ssh = paramiko.SSHClient() ##開啟客戶端 賦給變量ssh
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ##自動創建遠程密鑰
ssh.connect(host,username=‘root‘,password=‘Taren1‘) ##連接輸入用戶名密碼
ssh.exec_command(‘mkdir /root/桌面/到此一遊‘) ##遠程執行命令
b=[‘176.121.205.%d‘%i for i in xrange(23,60)] ##利用for循環創建列表
for j in b: ##利用for循環取出列表,取一個循環一次
a=threading.Thread(target=myssh,args=[j])
a.start()

正則表達式

python錯誤和異常,re模塊,多線程,paramiko模塊