#!/usr/bin/env python |
|
#-*- coding:utf-8 -*- |
|
import os,sys,time,shutil,re |
|
from _ast import Num |
|
from django.db.models.sql.datastructures import Join |
|
|
|
''' |
|
--------------------------- |
|
此腳本用於以前學習內容的回顧 |
|
裝飾器還須要多看,目前仍是不是很清楚 |
|
類的繼承 |
|
property須要學習 |
|
抽象方法/私有字段/私有方法/靜態字段/靜態方法 |
|
__call__方法 |
|
__del__方法 |
|
--------------------------- |
|
''' |
|
#-------------------遞歸例子--------------------- |
|
''' |
|
#函數 |
|
def fun2(n): |
|
result = n |
|
for i in range(1,n): |
|
result *= i |
|
return result |
|
|
|
print 'fun2',fun2(5) |
|
|
|
|
|
#遞歸 |
|
def fun3(n): |
|
if n == 1: |
|
return 1 |
|
else: |
|
return n*fun3(n-1) |
|
|
|
print 'fun3',fun3(5) |
|
|
|
|
|
def fun(n): |
|
if n == 1: |
|
return 1 |
|
else: |
|
return n+fun(n-1) |
|
|
|
print fun(5) |
|
|
|
|
|
def fun1(x): |
|
if x == 0 or x ==1: |
|
return 1 |
|
else: |
|
return fun1(x-1) + fun1(x-2) |
|
|
|
print fun1(5) |
|
|
|
|
|
若是說兔子在出生兩個月後,就有繁殖能力,在擁有繁殖能力以後,這對兔子每月能生出 |
|
一對小兔子來。假設全部兔子都不會死去,可以一直幹下去,那麼一年以後能夠繁殖多少對 |
|
兔子呢? |
|
|
|
|
|
def tuzi(x): |
|
if x==1 or x==2: |
|
return 1 |
|
else: |
|
return tuzi(x-1)+tuzi(x-2) |
|
|
|
print tuzi(5) |
|
|
|
|
|
|
|
''' |
|
#-------------------遞歸 遍歷目錄下全部文件--------------------- |
|
|
|
''' |
|
#----------列表推導式列出全部文件 |
|
path = 'd:/python' |
|
os.chdir(path) |
|
a = [i for i in os.listdir(path) if os.path.isfile(i)] |
|
for x in a: |
|
print x |
|
|
|
#等同下面 |
|
for i in os.listdir('d:/python'): |
|
a = os.path.join('d:/python',i) |
|
print os.path.isfile(a) |
|
if os.path.isfile(i): |
|
print i |
|
|
|
path = 'd:/python' |
|
os.chdir(path) |
|
a = [i for i in os.listdir(path) if os.path.isfile(i) and os.path.splitext(i)[1] =='.zip'] |
|
print a |
|
|
|
|
|
path = 'd:/python' |
|
|
|
|
|
#----------遞歸方式 |
|
#可採用os.path.join拼接路徑的方式,來確認完整路徑,避免使用路徑切換,os.chdir |
|
def scan(path): |
|
for file in os.listdir(path): |
|
file_dir = os.path.join(path,file) |
|
if not os.path.isdir(file_dir): |
|
print file_dir |
|
else: |
|
scan(file_dir) |
|
scan(path) |
|
|
|
#----------os.walk方式 |
|
g = os.walk('d:/python') |
|
for path,folder,filelist in g: |
|
print filelist |
|
for filename in filelist: |
|
print os.path.join(path,filename) |
|
''' |
|
|
|
#------------------文件夾整理----------------------- |
|
|
|
|
|
|
|
|
|
''' |
|
def file_summary(path): |
|
for file in os.listdir(path): |
|
file_dir = os.path.join(path,file) |
|
if os.path.isdir(file_dir): |
|
file_summary(file_dir) |
|
else: |
|
file_name = ''.join(re.findall('201\d{5}',file)) |
|
Folder_name = os.path.join(path,file_name) |
|
try: |
|
if not os.path.exists(Folder_name): |
|
os.mkdir(Folder_name) |
|
wjy_num += 1 |
|
try: |
|
if file_dir not in os.listdir(Folder_name): |
|
print file_dir |
|
shutil.move(file_dir,Folder_name) |
|
except: |
|
print 'error' |
|
file_num += 1 |
|
except: |
|
print '沒找到日期' |
|
|
|
file_summary(path) |
|
''' |
|
|
|
|
|
# print ''' |
|
# ------------------------------------------------------- |
|
# 此腳本用於整理文件,按圖片名日期進行分類,每一個日期建 |
|
# 一個新的文件夾,將同一天的文件放入文件夾中 |
|
# ------------------------------------------------------- |
|
# ''' |
|
|
|
''' |
|
def fodler_time_fengnei(path): |
|
wjy_num = 0 |
|
file_num = 0 |
|
os.chdir(path) |
|
for i in os.listdir(path): |
|
#print i |
|
Folder_file = ''.join(re.findall('201\d{5}',i)) |
|
#print Folder_file |
|
try: |
|
#lock.acquire() |
|
if not os.path.exists(Folder_file): |
|
os.mkdir(Folder_file) |
|
wjy_num += 1 |
|
try: |
|
if i not in os.listdir(Folder_file): |
|
shutil.move(i,Folder_file) |
|
|
|
except: |
|
print 'error' |
|
#lock.release() |
|
file_num += 1 |
|
except: |
|
print '沒找到日期' |
|
print '處理了%d個文件'%file_num |
|
print '建立了%d個文件夾'%wjy_num |
|
print '分類完成' |
|
#print os.getcwd() |
|
def folder_vedio(path): |
|
os.chdir(path) |
|
#os.walk 獲得一個三元數組:路徑,路徑下的文件夾,文件 |
|
for i,k,v in os.walk(path): |
|
print i,k,v |
|
#迭代文件夾目錄 |
|
for folder in k: |
|
#進入每一個文件夾 |
|
os.chdir(folder) |
|
#迭代當前文件夾下的文件 |
|
for img in os.listdir(os.curdir): |
|
print img |
|
try: |
|
ext = img.split('.')[1] #獲得擴展名 |
|
print ext |
|
except: |
|
print 'error' |
|
if ext != 'jpg': #若是不是圖片文件 |
|
shutil.move(img, os.pardir) #移動到上一級目錄 |
|
|
|
os.chdir(os.pardir) |
|
|
|
#此函數用於將文件夾下的全部文件移動到指定的目錄中, |
|
#目前只有一層目錄功能 2016/12/27更新 |
|
def file_move(path,dst): |
|
os.chdir(path) #這裏必定要先進入到須要整理的目錄中 |
|
for i,k,v in os.walk(path): |
|
print i,k |
|
for folder in k: |
|
try: |
|
print os.getcwd() |
|
os.chdir(folder) |
|
for file in os.listdir(os.curdir): |
|
shutil.move(file, dst) |
|
except Exception,e: |
|
print e |
|
os.chdir(os.pardir) |
|
|
|
#如下用於移動文件,已成功實現所需功能 2016/12/28 |
|
def file_move(path,dst): |
|
os.chdir(path) |
|
n = 1 |
|
#dst = 'd:\\pooto\\p' |
|
#這裏用os.walk產生一個生成器,再經過迭代,列出目錄下全部的子目錄和文件 |
|
#os.walk以遞歸的方式遍歷當前目錄下的全部文件和目錄 |
|
for path1,file_dir,fs in os.walk(path): |
|
# print 'PATH 第%d次:'%n,path1 |
|
# print 'DIR:第%d次:'%n,file_dir |
|
# print 'FS第%d次:'%n,fs |
|
#確認當前目錄下是否有文件,沒有跳過 |
|
if fs==[]: |
|
pass |
|
#print '空的' |
|
else: |
|
file_num = 0 |
|
try: |
|
#若是有文件,迭代一下 |
|
for file in fs: |
|
#進入目錄 |
|
os.chdir(path1) |
|
#print '當前路徑是: '+os.getcwd()+', 當前文件是: '+file |
|
ext = file.split('.')[-1] #取最後一個就是擴展名 |
|
#print ext |
|
if ext == 'jpg' or ext =='png': |
|
try: |
|
shutil.move(file,dst) #移動到指定目錄 |
|
#print 'move was ok' |
|
file_num += 1 #統計移動文件的個數 |
|
except Exception,e: #出錯了,提示緣由 |
|
#print e |
|
print u'移動文件出錯了,快查一下緣由' |
|
#shutil.move(file,del_dir) |
|
except: |
|
print u'迭代序列出錯了' |
|
print u'移動了%d個文件'% file_num |
|
os.chdir(os.pardir) #當前目錄完成了,跳回主目錄,進行下一次迭代目錄 |
|
n += 1 |
|
|
|
if __name__ == '__main__': |
|
|
|
print |
|
------------------------------------------------- |
|
請選擇你須要的功能: |
|
1. 對圖片按名稱分組 |
|
2. 對圖片按後綴分組 |
|
3. 將文件移動到另外一目錄中 |
|
------------------------------------------------- |
|
|
|
|
|
select1 = raw_input(':') |
|
start_time = time.time() |
|
if select1 == '1': |
|
#lock = threading.Lock() |
|
path = raw_input(u'如:g:/software/DIM :').strip() |
|
fodler_time_fengnei(path) |
|
# t1 = threading.Thread(target=fodler_time_fengnei,args=(path,)) |
|
# t2 = threading.Thread(target=fodler_time_fengnei,args=(path,)) |
|
# t3 = threading.Thread(target=fodler_time_fengnei,args=(path,)) |
|
elif select1 =='2': |
|
pass |
|
elif select1 == '3': |
|
print u'源文件夾:' |
|
path = raw_input(u'如:g:/software/DIM :').strip() |
|
dst = raw_input(u'目標文件夾:').strip() |
|
file_move(path, dst) |
|
# 多線程沒什麼效果 |
|
# t1 = Thread(target=file_move,args=(path,dst)) |
|
# t2 = Thread(target=file_move,args=(path,dst)) |
|
# t3 = Thread(target=file_move,args=(path,dst)) |
|
# p1.start() |
|
# print 't1' |
|
# t2.start() |
|
# print 't2' |
|
# t3.start() |
|
# print 't3' |
|
end_time = time.time() |
|
print u'總共花了%.2f秒'%(end_time-start_time) |
|
|
|
# path = raw_input('[eg:g:/software/DIM] :').strip() |
|
# #os.chdir(path) |
|
# file_num = 0 |
|
# wjy_num = 0 |
|
# # folder_vedio(path) |
|
# fodler_time_fengnei(path) |
|
# print '總共整理了%d個文件'%file_num |
|
# print '總共建立了%d個文件夾'%wjy_num |
|
|
|
|
|
|
|
''' |
|
|
|
#------------------局部變量----------------------- |
|
''' |
|
var = 1 |
|
def a(): |
|
global var |
|
var += 1 |
|
var1 = 2 |
|
# print var |
|
def b(): |
|
print var1 |
|
nolocal #這裏2.7好像有問題,3.x好像是好的 |
|
var1 = 5 |
|
#print var1 |
|
b() |
|
|
|
a() |
|
''' |
|
|
|
|
|
#------------------------Pexpect練習---------------------- |
|
|
|
''' |
|
用於登陸Cisco設備並獲取相關信息,每次一個命令,完成後自動退出 |
|
適用於Linux |
|
''' |
|
''' |
|
def get(pe,cmd): |
|
login = 'telnet %s' % pe |
|
username = 'pingtest' |
|
password = 'pwdtest' |
|
tn = pexpect.spawn(login,timeout = 300) |
|
index = tn.expect(["Username",pexpect.EOF, pexpect.TIMEOUT]) |
|
if index == 0: |
|
tn.expect('Username:') |
|
tn.sendline(username) |
|
tn.expect('Password:') |
|
tn.sendline(password) |
|
tn.expect('#') |
|
tn.sendline(cmd) |
|
tn.sendline(' ') |
|
tn.expect('#') |
|
result = tn.before |
|
tn.sendline('exit') |
|
print result |
|
elif index == 1: |
|
print 'pexpect.EOF' |
|
else: |
|
print 'pexpect.TIMEOUT' |
|
|
|
|
|
if __name__ == '__main__': |
|
tupe1 = { |
|
'Mon':'星期一', |
|
'Tue':'星期二', |
|
'Wen':'星期三', |
|
'Thu':'星期四', |
|
'Fri':'星期五', |
|
'Sat':'星期六', |
|
'Sun':'星期天' |
|
} |
|
wenday = time.strftime('%a') |
|
xiqi = tupe1[wenday] |
|
while True: |
|
print '\n' |
|
pe = (raw_input('請輸入你須要登陸的PE[退出請用q]:')).strip() |
|
print '\n' |
|
if pe == 'q': |
|
break |
|
else: |
|
cmd = (raw_input('請輸入你須要執行的命令[退出請用q]:')).strip() |
|
if cmd == 'q': |
|
break |
|
print '\n\n' |
|
print '當前查詢時間:%s'%((time.strftime('%Y/%m/%d %H:%M:%S'))+' '+ xiqi) |
|
print '-----------------------------------------------------' |
|
print '\n' |
|
get(pe,cmd) |
|
|
|
''' |
|
|
|
|
|
#------------------------裝飾器實驗1---------------------- |
|
# def out(fun): |
|
# def watter(): |
|
# print '以前出現' |
|
# fun() |
|
# print '以後出現' |
|
# return watter |
|
# |
|
# @out |
|
# def fun1(): |
|
# print '這是Fun1的內容' |
|
# |
|
# fun1() |
|
# ---------帶參數的裝飾器 |
|
# def out(fun): |
|
# def watter(args): |
|
# print '以前出現' |
|
# fun(args) |
|
# print '以後出現' |
|
# return watter |
|
# |
|
# @out |
|
# def fun1(args): |
|
# print '這是Fun1的內容',args |
|
# |
|
# fun1(100) |
|
|
|
#---------帶返回的裝飾器 |
|
# def out(fun): |
|
# def watter(args): |
|
# print '以前出現' |
|
# a =fun(args) |
|
# print '以後出現' |
|
# print a |
|
# return watter |
|
# |
|
# @out |
|
# def fun1(args): |
|
# return u'這是Fun1的內容',args |
|
# |
|
# fun1(100) |
|
|
|
#-----下面這個例子很好說明的裝飾器的運行 |
|
# def timeslong(func): |
|
# def call(): |
|
# start = time.clock() |
|
# print("It's time starting ! ") |
|
# func() |
|
# print("It's time ending ! ") |
|
# end = time.clock() |
|
# return "It's used : %s ." % (end - start) |
|
# return call |
|
# |
|
# @timeslong |
|
# def f(): |
|
# y = 0 |
|
# for i in range(10): |
|
# y = y + i + 1 |
|
# print(y) |
|
# return y |
|
# |
|
# print(f()) |
|
|
|
|
|
#------------------------property--------------------- |
|
|
|
# class A: |
|
# def __init__(self): |
|
# print '這是A的Self' |
|
# |
|
# def B(self): |
|
# print '這是B的方法' |
|
# |
|
# @property |
|
# def C(self): |
|
# # print '這是C的方法' |
|
# return '這是C的方法' |
|
# |
|
# a = A() |
|
# print a |
|
# print a.B() |
|
# print a.C |
|
# |
|
# |
|
# class C: |
|
# def __init__(self): |
|
# self._x = None |
|
# |
|
# @property |
|
# def x(self): |
|
# """I'm the 'x' property.""" |
|
# return self._x |
|
# |
|
# @x.setter |
|
# def x(self, value): |
|
# self._x = value |
|
# |
|
# @x.deleter |
|
# def x(self): |
|
# del self._x |
|
# |
|
# |
|
# c1 = C() |
|
# c1.x = 3 |
|
# print c1.x |
|
|
|
######################################################### |
|
|
|
|
|
#------------------------抽象方法--------------------- |
|
#抽象類抽象方法==接口 |
|
from abc import ABCMeta,abstractmethod |
|
|
|
# class Bar: |
|
# __metaclass__ = ABCMeta |
|
# |
|
# @abstractmethod |
|
# def get(self): |
|
# raise 'no define get ' |
|
# |
|
# class Car(Bar): |
|
# def __init__(self): |
|
# print '這是一個Car的類' |
|
# |
|
# # def get(self): |
|
# # print 'aaa' |
|
# |
|
# car = Car() |
|
|
|
|
|
# class Bar: |
|
# __metaclass__ = ABCMeta |
|
# |
|
# @abstractmethod |
|
# def Fun(self): |
|
# pass |
|
# |
|
# class Foo(Bar): |
|
# def __init__(self): |
|
# print '__init__' |
|
# |
|
# # def Fun(self): |
|
# # print '告警' |
|
# |
|
# f = Foo() |
|
# f.Fun() |
|
|
|
######################################################### |
|
|
|
#------------------------私有字段/方法--------------------- |
|
|
|
# class Bar: |
|
# def __init__(self): |
|
# self.__x = 10 |
|
# |
|
# def __get(self): |
|
# print '這是私有方法' |
|
# #能夠經過動態方法調用私有方法 |
|
# def show(self): |
|
# print self.__get() |
|
# |
|
# b = Bar() |
|
# print b._Bar__x #強制使用類的方式來訪問私有方法 |
|
# print b.show() |
|
|
|
#------------------------靜態字段/方法--------------------- |
|
|
|
# class Bar: |
|
# name = 'liyang' |
|
|
|
# @staricmethod |
|
# def hello(): |
|
# print 'Hello' |
|
# |
|
# b = Bar() |
|
# print b.name |
|
# print b.hello() |
|
# 靜態字段和靜態方法無需實例化,可經過用類來調用 |
|
######################################################### |
|
|
|
|
|
#------------------------靜態字段/方法--------------------- |
|
#__call__ 最後執行 |
|
#__del__ 何時使用,直接用對象加括號就能夠調用了 |
|
|
|
# class Bar: |
|
# def __init__(self): |
|
# print '這是__init__' |
|
# |
|
# def __call__(self): |
|
# print '這是__call__' |
|
# |
|
# def __del__(self): |
|
# print '我就要被刪除了' |
|
# |
|
# def show(self): |
|
# print '這是一個顯示的函數' |
|
# |
|
# b = Bar() |
|
# print b |
|
# print b() #調用call方法 |
|
# print b.show() |
|
|
|
######################################################### |
|
|
|
|
|
#------------------------類的繼承--------------------- |
|
#新式類必須加object,同時多重繼承是廣度優先,經典類是深度優先 |
|
# class A(object): |
|
# def __init__(self): |
|
# print '這是A的__init__' |
|
# |
|
# def show(self): |
|
# print '這是顯示A的類' |
|
# |
|
# class B(A): |
|
# def __init__(self): |
|
# #A.__init__(self) |
|
# super(B,self).__init__() #這裏的super值爲當前類,主類必須是新式類 |
|
# print '這是B的__init__' |
|
# |
|
# class C(A): |
|
# def __init__(self): |
|
# print '這是C的__init__' |
|
# |
|
# def show(self): |
|
# print '這是顯示C的類' |
|
# |
|
# class D(B,C): |
|
# def __init__(self): |
|
# print '這是D的__init__' |
|
# |
|
# |
|
# # b1 = B() |
|
# # print b1 |
|
# |
|
# d1 = D() |
|
# print d1 |
|
# print d1.show() |
|
|
|
#--------------------使用super也能夠在經黃類中避免深度優先的問題------------------ |
|
# class A(): |
|
# def __init__(self): |
|
# print '這是A的__init__' |
|
# |
|
# def show(self): |
|
# print '這是顯示A的類' |
|
# |
|
# class B(A): |
|
# def __init__(self): |
|
# #A.__init__(self) |
|
# super().__init__() #這裏的super,能夠避免深度優先的問題 |
|
# print '這是B的__init__' |
|
# |
|
# class C(A): |
|
# def __init__(self): |
|
# print '這是C的__init__' |
|
# |
|
# def show(self): |
|
# print '這是顯示C的類' |
|
# |
|
# class D(B,C): |
|
# def __init__(self): |
|
# print '這是D的__init__' |
|
|
|
# |
|
# b1 = B() |
|
# print b1 |
|
|
|
# d1 = D() |
|
# print d1 |
|
# print d1.show() |
|
|
|
######################################################### |
|
|
|
|
|
|
|
''' |
|
------------------------------ |
|
字符編碼:ASCII/Unicode/UTF-8 |
|
|
|
decode的做用是將其餘編碼的字符串轉換成unicode編碼, |
|
encode的做用是將unicode編碼轉換成其餘編碼的字符串, |
|
Unicode<----decode----UTF |
|
Unicode-----encode---->UTF |
|
|
|
|
|
------------------------------ |
|
''' |
|
|
|
#------------------------編碼學習--------------------- |
|
# name = '李明' |
|
# print '第一次',name |
|
# if not isinstance(name,unicode): |
|
# name = name.decode('utf-8') |
|
# print name |
|
# |
|
|
|
######################################################### |
|
|
|
# import datetime |
|
# #顯示當前日期 |
|
# print datetime.date.today() |
|
# print datetime.date.today() - datetime.timedelta(days = 2) |
|
# #顯示指定日期 |
|
# print datetime.date(2015, 4, 2) |
|
# |
|
# print datetime.time(1,2,3) |
|
|
|
#------------------------生成器--------------------- |
|
|
|
# def a(): |
|
# for i in range(10): |
|
# yield i |
|
# |
|
# a1 = a() |
|
# print a1.next() |
|
# print a1.next() |
|
######################################################### |
|
|
|
|
|
|
|
#--------------------Excel Into Mysql-------------------- |
|
# import pymysql |
|
# import xlrd |
|
# |
|
# def xls_info(): |
|
# xls = xlrd.open_workbook('d:/bb.xls') #打開Excel |
|
# sheets = xls.sheet_names() #獲取表 |
|
# table = xls.sheet_by_name(sheets[2]) #獲得須要的表名 |
|
# rows = table.nrows #獲取表的總行數 |
|
# return table,rows #返回表名和行數 |
|
# |
|
# def mysql_info(): |
|
# myconn = pymysql.Connect('127.0.0.1','root','','django') #鏈接Mysql |
|
# mycur = myconn.cursor() #建立遊標 |
|
# mycur.execute('set names utf8') #指定爲utf8編碼 |
|
# #建立表格 |
|
# # table_create = 'CREATE TABLE mysql_test(name varchar(20),ip varchar(20));' |
|
# # mycur.execute(table_create) |
|
# mycur.execute('desc mysql_test') |
|
# #插入表格的命令 |
|
# insert_sql = 'insert into mysql_test values(%s,%s);' |
|
# |
|
# #調用上個函數的值,獲得表名和行數 |
|
# table,rows=xls_info()[0],xls_info()[1] |
|
# for i in range(0,rows): #迭代每行 |
|
# xls_line = table.row_values(i) #獲得每行的信息 |
|
# print xls_line |
|
# print mycur.execute(insert_sql,xls_line) #插入每行的數據到數據庫中 |
|
# mycur.execute('select * from mysql_test') |
|
# print mycur.fetchall() |
|
# myconn.commit() #事務提交 |
|
# mycur.close() |
|
# myconn.close() |
|
# |
|
# mysql_info() |
|
|
|
|
|
#-------------Mysql獲得字典------------------------ |
|
|
|
#!/usr/bin/env python |
|
# encoding: utf-8 |
|
|
|
#Created on 2017年1月13日 |
|
#@author: Administrator |
|
''' |
|
import pymysql |
|
|
|
def main(): |
|
try: |
|
conn = pymysql.connect(host = '127.0.0.1', user = 'root', passwd = '', db = 'django') |
|
cur = conn.cursor(cursor=pymysql.cursors.DictCursor) |
|
cur.execute("select * from mysql_test") |
|
qur_result = cur.fetchall() |
|
cur.close() |
|
conn.close() |
|
# for record in qur_result: |
|
# user = record[0] |
|
# passwd = record[1] |
|
except pymysql.Error,e: |
|
print 'Mysql Error Msg:',e |
|
#print type(qur_result) |
|
for k in qur_result: |
|
#print k |
|
for i,j in k.items(): |
|
print j |
|
|
|
|
|
|
|
if __name__ == '__main__': |
|
main() |
|
|
|
''' |
|
|
|
#-------------------線程練習------------------------ |
|
import threading |
|
from IPython.utils.io import stdin, stderr |
|
from sys import stdout |
|
import paramiko |
|
|
|
|
|
''' |
|
|
|
def Foo(args): |
|
for i in range(10): |
|
print i |
|
time.sleep(1) |
|
|
|
print '開始' |
|
t1 = Thread(target=Foo,args = (1,)) |
|
#t1.setDaemon(True) |
|
t1.start() |
|
print t1.getName() |
|
|
|
''' |
|
|
|
#-------------------自定義線程練習------------------------ |
|
''' |
|
|
|
class MyThread(Thread): |
|
def run(self): |
|
Thread.run(self) |
|
print 'run' |
|
for i in range(10): |
|
print i |
|
time.sleep(1) |
|
|
|
|
|
def Foo(args): |
|
print '這是個人新函數' |
|
|
|
t1 = MyThread(target=Foo,args =(1,)) |
|
t1.start() |
|
print t1.getName() |
|
print t1.isDaemon() |
|
print t1.join(3) |
|
''' |
|
#-------------------生產消費模型------------------------ |
|
''' |
|
#兩個類都是同樣的,要用到隊列,有兩個判斷條件,是否爲空,是否爲滿 |
|
import Queue |
|
class ShenChang(Thread): |
|
def __init__(self,name,que): |
|
self.__Name = name |
|
self.__Que = que |
|
Thread.__init__(self) |
|
|
|
def run(self): |
|
while True: |
|
if self.__Que.full(): |
|
print '作完了,能夠休息一下了' |
|
time.sleep(1) |
|
else: |
|
self.__Que.put('xxx') |
|
print self.__Name,'生產包子' |
|
Thread.run(self) |
|
|
|
que = Queue.Queue(maxsize=30) |
|
|
|
for x in range(10): |
|
name = 'alan%d'%x |
|
s1 = ShenChang(name,que) |
|
s1.start() |
|
|
|
class XiaFei(Thread): |
|
def __init__(self,name,que): |
|
self.__Name = name |
|
self.__Que = que |
|
Thread.__init__(self) |
|
|
|
def run(self): |
|
while True: |
|
if self.__Que.empty(): |
|
print '沒有吃的了,先休息一下吧' |
|
time.sleep(2) |
|
else: |
|
self.__Que.get() |
|
print self.__Name,'吃了一個包子' |
|
Thread.run(self) |
|
|
|
for i in range(3): |
|
name = 'name%d'%i |
|
t1 = XiaFei(name,que) |
|
t1.start() |
|
|
|
''' |
|
|
|
#-------------------paramiko用戶名和密碼------------------------ |
|
''' |
|
import paramiko |
|
|
|
ssh = paramiko.SSHClient() |
|
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
|
ssh.connect('114.28.37.23', 50022, 'root', '263!@#$%^&*()') |
|
print 'connected..............' |
|
while True: |
|
cmd = raw_input('請輸入你要執行的命令[退出q] : ') |
|
if cmd == 'q': |
|
print '\nbye---------\n------------' |
|
sys.exit() |
|
stdin,stdout,stderr = ssh.exec_command(cmd) |
|
print stdout.read() |
|
ssh.close() |
|
|
|
''' |
|
|
|
#-------------------paramiko Key----------------------- |
|
|
|
''' |
|
#在執行前要手工在目標機器上輸入如下命令: |
|
# ssh-keygen -t rsa 建立密鑰 |
|
# ssh-copy-id root@114.28.37.209 將公鑰Copy到服務器 |
|
|
|
|
|
private_key_path = '/root/.ssh/id_rsa' |
|
key = paramiko.RSAKey.from_private_key_file(private_key_path) |
|
|
|
paramiko.util.log_to_file('paramiko.log') #加入日誌 |
|
ssh = paramiko.SSHClient() |
|
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
|
ssh.connect('127.0.0.1', 22, username='root', pkey=key) |
|
stdin,stdout,stderr = ssh.exec_command('ls') |
|
print stdout.read() |
|
ssh.close() |
|
|
|
''' |
|
#-------------------paramiko 建立刪除顯示 ssh router----------------------- |
|
''' |
|
ssh = paramiko.SSHClient() |
|
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
|
|
|
#IP,Port,Username,Password='114.141.185.5',22, 'opsinfo', 'pwdops' |
|
IP,Port,Username,Password='114.141.185.5',22, 'opsinfo', 'pwdops' |
|
try: |
|
ssh.connect(IP,Port,Username,Password, look_for_keys=False, allow_agent=False) |
|
except Exception,e: |
|
print e |
|
print 'ssh connection established to %s' % IP |
|
|
|
|
|
remote_conn = ssh.invoke_shell() |
|
#print remote_conn.recv(1000) |
|
remote_conn.send('\n') |
|
remote_conn.send('sh ip int bri\n') |
|
time.sleep(2) |
|
print remote_conn.recv(10000) |
|
#stdin,stdout,stderr = ssh.exec_command('sh ver') |
|
# ssh.connect('1172.16.4.1', 23, 'opsinfo', 'pwdops') |
|
# stdin,stdout,stderr = ssh.exec_command('sh ver') |
|
#print stdout.read() |
|
ssh.close() |
|
''' |
|
#-------------socket登陸路由器測試----------------- |
|
''' |
|
import socket |
|
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) |
|
ip_port =('172.16.4.1',23) |
|
sock.connect(ip_port) |
|
sock.send('opsinfo\n') |
|
time.sleep(1) |
|
sock.send('pwdops\n') |
|
time.sleep(1) |
|
sock.send('sh ver') |
|
time.sleep(1) |
|
data1 = sock.recv(1024) |
|
time.sleep(1) |
|
print data1 |
|
|
|
''' |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#-------------------paramiko上傳下載----------------------- |
|
''' |
|
print os.getcwd() |
|
os.chdir('d:/') |
|
print os.getcwd() |
|
t = paramiko.Transport(('114.28.37.23', 50022)) |
|
t.connect(username='root', password='263!@#$%^&*()') |
|
sftp = paramiko.SFTPClient.from_transport(t) |
|
local_path = 'd:/lsdksmq-v2.0.0.200.zip' |
|
base_name = os.path.basename(local_path) |
|
remote_path = '/home/'+base_name |
|
sftp.put(local_path,remote_path) #上傳 |
|
|
|
#sftp.get(remote_path,local_path) #下載 |
|
|
|
t.close() |
|
''' |
|
''' |
|
t = paramiko.Transport(('114.28.13.143', 22)) |
|
t.connect(username='root', password='111111') |
|
sftp = paramiko.SFTPClient.from_transport(t) |
|
|
|
print sftp.listdir('/smb') |
|
print sftp.rename('/smb/Flow.rrd.bak','/smb/Flow.rrd.bak1') |
|
print sftp.mkdir('/home/aa1',0755) |
|
print sftp.listdir('/home') |
|
''' |
|
#-------------------paramiko+threading----------------------- |
|
|
|
''' |
|
用函數將Paramiko的代碼包起來,再經過我線程來同時操做 |
|
|
|
def SshCmd(server,username,password,cmd): |
|
ssh = paramiko.SSHClient() |
|
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
|
ssh.connect(server,50022,username, password) |
|
stdin,stdout,stderr = ssh.exec_command(cmd) |
|
print server, '\n %s'% cmd, |
|
print stdout.read() |
|
ssh.close() |
|
|
|
|
|
if __name__ =='__main__': |
|
username = 'root' |
|
password = '263!@#$%^&*()' |
|
cmds = ['ls -lh /'] |
|
ips = ['114.28.37.23','114.28.37.24'] |
|
for ip in ips: |
|
for cmd in cmds: |
|
temp = Thread(target=SshCmd,args=(ip,username,password,cmd)) |
|
temp.start() |
|
|
|
''' |
|
|
|
|
|
|
|
|
|
#-------------------threading 異步模型----------------------- |
|
''' |
|
import threading |
|
|
|
def shengchang(): |
|
print u'P:作包子………………' |
|
event.wait() |
|
event.clear() |
|
print u'P:作包子' |
|
time.sleep(3) |
|
print u'P:你的包子作好了' |
|
event.set() |
|
|
|
|
|
def xiaofei(): |
|
print u'C:買包子去………………' |
|
event.set() |
|
time.sleep(2) |
|
print u'C:等作包子……………… ' |
|
#print event.wait() |
|
while True: |
|
if event.isSet(): |
|
print u'C:太好了' |
|
break |
|
else: |
|
print '作其餘事情去了……' |
|
time.sleep(0.08) |
|
|
|
event = threading.Event() |
|
p = threading.Thread(target=shengchang) |
|
c = threading.Thread(target=xiaofei) |
|
p.start() |
|
c.start() |
|
|
|
''' |
|
|
|
#-------------------IP換算---------------------- |
|
''' |
|
def ch1(num): |
|
s = [] |
|
for i in range(4): |
|
s.append(str(num%256)) |
|
print s |
|
num /= 256 |
|
return '.'.join(s[::-1]) |
|
print ch1(123456789) |
|
|
|
|
|
#用lambda的方式,整數toIP 地址 一行代碼搞定 |
|
ch2 = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)]) |
|
print ch2(123456789) |
|
|
|
#用lambda的方式,IP地址轉換到整數 |
|
ch3 = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])]) |
|
print ch3('7.91.205.21') |
|
|
|
''' |
|
|
|
#-------------------IP敬意計算---------------------- |
|
import os |
|
''' |
|
def getip(ip, count): |
|
count = int(count) |
|
ip2 = int(ip.split('.')[-2]) |
|
ip1 = int(ip.split('.')[-1]) |
|
ip_before = '%s.%s' % (ip.split('.')[0], ip.split('.')[1]) |
|
|
|
for i in range(0,count,4): |
|
new_ip1 = ip1 + i |
|
if 11 <= new_ip1 <= 254: |
|
print '%s.%s.%s' % (ip_before, str(ip2), str(new_ip1)) |
|
else: |
|
new_ip2 = ip2 + int(new_ip1/254) |
|
new_ip1 = new_ip1%254 + 0 |
|
print '%s.%s.%s' % (ip_before, str(new_ip2), str(new_ip1)) |
|
|
|
if __name__ == '__main__': |
|
getip('10.0.1.0', 1000) |
|
''' |
|
''' |
|
def getip(ip, count,step): |
|
count = int(count) |
|
|
|
ip1 = int(ip.split('.')[-1]) |
|
ip2 = int(ip.split('.')[-2]) |
|
ip3 = int(ip.split('.')[-3]) |
|
ip4 = int(ip.split('.')[-4]) |
|
ip_before = '%s.%s' % (ip.split('.')[0], ip.split('.')[1]) |
|
|
|
for i in range(0,count,step): |
|
new_ip1 = ip1 + i |
|
#print '%s.%s.%s' % (ip_before, str(ip2), str(new_ip1)) |
|
if new_ip1 <= 255: |
|
pass |
|
print '%s.%s.%s' % (ip_before, str(ip2), str(new_ip1)) |
|
else : |
|
new_ip2 = ip2 + int(new_ip1/256) |
|
if new_ip2 <= 255: |
|
new_ip1 = new_ip1%256 |
|
print '%s.%s.%s' % (ip_before, str(new_ip2), str(new_ip1)) |
|
else: |
|
new_ip3 = ip3 + int(new_ip2/256) |
|
new_ip2 = ip1 + int(new_ip1/256) |
|
new_ip1 = new_ip1%256 |
|
#print 'ip1------------:',new_ip1 |
|
new_ip2 = 0 |
|
if new_ip1 >= (256/step-1)*step: |
|
new_ip2 += 1 |
|
new_ip1 = new_ip1%256 |
|
#print 'ip2-----:',new_ip2 |
|
print '%s.%s.%s.%s' % (str(ip4),str(new_ip3), str(new_ip2), str(new_ip1)) |
|
|
|
|
|
if __name__ == '__main__': |
|
getip('10.0.255.192',830,32) |
|
|
|
''' |
|
|
|
#---------------------pexpect 交互鏈接------------------------ |
|
''' |
|
#!/usr/bin/env python |
|
#coding=utf-8 |
|
|
|
import pexpect |
|
import time,re |
|
import pymysql |
|
|
|
loginprompt = '#' |
|
def get(login_ip): |
|
login = 'telnet %s' % login_ip |
|
tn = pexpect.spawn(login,timeout = 300) |
|
#tn.expect('Username:') |
|
flag = tn.expect(["login","Username:", "(?i)Unknown host", pexpect.EOF, pexpect.TIMEOUT]) |
|
username = 'opsinfo' |
|
password = 'pwdops' |
|
if flag == 0 or flag == 1: |
|
tn.sendline(username) |
|
tn.expect('Password:') |
|
tn.sendline(password) |
|
tn.expect(r'[#>]') |
|
print tn.before |
|
#交互開始 |
|
tn.interact() |
|
print 'Left interactv mode' |
|
else: |
|
print 'error' |
|
|
|
if __name__ == '__main__': |
|
login_ip = raw_input('IP: ') |
|
get(login_ip) |
|
''' |
|
|
|
|
|
|
|
#---------------------ping 主機------------------------ |
|
''' |
|
#!/usr/bin/env python |
|
import multiprocessing |
|
import subprocess |
|
import time |
|
|
|
start_time = time.time() |
|
host_list = ['192.168.100.254','1.1.1.1','192.168.100.253','114.28.127.2','114.28.127.72','114.28.127.70','114.28.127.12','114.28.127.56','114.28.127.102'] |
|
if len(host_list) > 30: |
|
process_number = 30 |
|
else: |
|
process_number = len(host_list) |
|
def ping_host(ipaddr): |
|
if subprocess.call('ping -c5 -W 1 %s > /dev/null' % ipaddr, shell=True) == 0: |
|
#if subprocess.call('ping -c1 -W 1 %s ' % ipaddr, shell=True) == 0: |
|
print '%s is OK' % ipaddr |
|
else: |
|
print '%s is DOWN' % ipaddr |
|
pool = multiprocessing.Pool(processes=10) |
|
for ip in host_list: |
|
pool.apply_async(ping_host,(ip,)) |
|
#pool.map(ping_host,host_list) |
|
pool.close() |
|
pool.join() |
|
|
|
end_time = time.time() |
|
print 'It is take %.2f seconds'%(start_time-end_time) |
|
''' |
|
|
|
#---------------------從文件中找出IP地址------------------------ |
|
''' |
|
import re |
|
f = file('d:\ip.txt','rb') |
|
set1 = set() |
|
for line in f.xreadlines(): |
|
try: |
|
ip = ''.join(re.findall('(?:\d+\.){3}\d{1,3}', line)) |
|
#print ip |
|
set1.add(ip) |
|
except: |
|
pass |
|
f.close() |
|
set1 = sorted(set1) |
|
#print set1 |
|
for i in set1: |
|
print i |
|
|
|
''' |
|
|
|
#---------------------用Pexpect登陸設備並測試Ping----------------------- |
|
''' |
|
#!/usr/bin/env python |
|
#-*- coding:utf-8 -*- |
|
|
|
import pexpect |
|
import re |
|
import time |
|
|
|
問題: |
|
1.迭代查詢和Ping包,第二次老是看不到查詢的結果,致使搜索錯誤,在Python中直接測試正常 |
|
2.另外一個問題:經過expect若是PIng不到,是否有返回結果,好像看不到 |
|
|
|
f = file('/smb/python_s8/day8/ip.txt','rb') |
|
|
|
username = 'pingtest' |
|
password = 'pwdtest' |
|
tn = pexpect.spawn('telnet 219-mr01') |
|
#index = tn.expect(["Username:",pexpect.EOF, pexpect.TIMEOUT]) |
|
try: |
|
#if index == 0: |
|
tn.expect('Username:') |
|
tn.sendline(username) |
|
tn.expect('Password:') |
|
tn.sendline(password) |
|
print 'auth is ok' |
|
x= 1 |
|
for line in f.xreadlines(): |
|
#print line |
|
tn.expect('#') |
|
#print 'is this running?' |
|
tn.sendline('sh ip vrf interface | inc %s' % line) |
|
tn.expect('#') |
|
result = tn.before |
|
tn.expect('#') |
|
# print len(result) |
|
print '-------------------this is %d result:---------------\n%s\n'%(x,result) |
|
ip = ''.join(re.findall('(?:\d+\.){3}\d{1,3}', result)) |
|
vrf = ''.join(re.findall('(\w{3,5}\d{3,6}\w+)',result)) |
|
print 'ip: %s , vrf: %s' %(ip,vrf) |
|
|
|
#這裏更改目標IP地址 |
|
ip1= ip.split('.') #分割IP |
|
if ip1[0] == '114': |
|
ip1[3] =str(int(ip.split('.')[-1])+1) #替換最後一個IP數字 |
|
else: |
|
ip1[3] =str(int(ip.split('.')[-1])-1) #替換最後一個IP數字 |
|
targetIP ='.'.join(ip1) |
|
|
|
#組合命令 |
|
cmd = 'ping vrf %s %s re 2'%(vrf,targetIP) |
|
print cmd |
|
try: |
|
tn.sendline(cmd) |
|
except: |
|
print 'error' |
|
time.sleep(10) |
|
|
|
tn.expect('#') |
|
#tn.expect('#') |
|
result1 = tn.before |
|
print result1 |
|
#tn.sendline('\r\r\r') |
|
x += 1 |
|
tn.sendline('exit') |
|
# elif index == 1: |
|
# print 'pexpect.EOF' |
|
# else: |
|
# print 'pexpect.TIMEOUT' |
|
except Exception,e: |
|
print e |
|
''' |
|
|
|
#---------------------Jump跳板機---------------------- |
|
|
|
#!/usr/bin/python |
|
# # coding:utf-8 |
|
# import sys |
|
# import time |
|
# import re |
|
# import pexpect |
|
# import os |
|
# import struct |
|
# import fcntl |
|
# import termios |
|
# import signal |
|
# import MySQLdb |
|
# |
|
|
|
# |
|
# def sigwinch_passthrough (sig, data): |
|
# winsize = getwinsize() |
|
# global child |
|
# child.setwinsize(winsize[0],winsize[1]) |
|
# |
|
# def getwinsize(): |
|
# if 'TIOCGWINSZ' in dir(termios): |
|
# TIOCGWINSZ = termios.TIOCGWINSZ |
|
# else: |
|
# TIOCGWINSZ = 1074295912L # Assume |
|
# s = struct.pack('HHHH', 0, 0, 0, 0) |
|
# x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s) |
|
# return struct.unpack('HHHH', x)[0:2] |
|
# |
|
# def getServersList(): |
|
# sqlStr = ''' select * from sys_info ''' |
|
# cursor.execute(sqlStr) |
|
# rows = cursor.fetchall() |
|
# strList = '' |
|
# for index, row in enumerate(rows): |
|
# strList += 'Hostname:%s , IP:\033[1;34;40m%s\033[0m \n' % (row[0],row[1]) |
|
# return strList |
|
# |
|
# def sshLogin(choice): |
|
# reip = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])') |
|
# if len ( reip.findall(choice) ) == 0: |
|
# print '\033[1;31;40mIP Error you entered.Please Enter again.\033[0m' |
|
# return |
|
# host = reip.findall(choice)[0] |
|
# sqlStr = ''' select count(*) from sys_info where ip='%s' ''' % host |
|
# cursor.execute(sqlStr) |
|
# rows = cursor.fetchall() |
|
# if rows[0][0] == 0: |
|
# print '\033[1;31;40mThe IP you entered is not in the list.\033[0m' |
|
# return |
|
# sqlStr = ''' select * from sys_info where ip='%s' ''' % host |
|
# cursor.execute(sqlStr) |
|
# rows = cursor.fetchall() |
|
# username =rows[0][2] |
|
# passwd =rows[0][3] |
|
# print 'ssh ' + username + '@' + host + ' ...' |
|
# global child |
|
# child = pexpect.spawn('ssh %s@%s' % (username,host)) |
|
# #child = pxssh.pxssh() |
|
# child.logfile = fout |
|
# #child.logfile = sys.stdout |
|
# #child.logfile_send = sys.stdout |
|
# signal.signal(signal.SIGWINCH, sigwinch_passthrough) |
|
# |
|
# winsize = getwinsize(); |
|
# child.setwinsize(winsize[0], winsize[1]) |
|
# flag = child.expect(['continue', 'password', pexpect.EOF, pexpect.TIMEOUT]) |
|
# #child.login (host, username, passwd, original_prompt='[$#>]') |
|
# #child.prompt() |
|
# #print flag |
|
# if flag == 0: |
|
# child.sendline('yes') |
|
# child.expect('.*password:.*') |
|
# child.sendline(passwd) |
|
# elif flag == 1: |
|
# child.sendline(passwd) |
|
# child.interact() |
|
# pass |
|
# |
|
# if __name__ == '__main__': |
|
# DBHOST='127.0.0.1' |
|
# DBNAME='jump' |
|
# DBUSER = 'root' |
|
# DBPWD = 'db03dUNG' |
|
# FILENAME = '/data/build/command_jump.log' |
|
# WELCOME = '''\033[1;34;40m### Welcome use JumpServer to Login. ### \033[0m ''' |
|
# CHOICE = """1. Type \033[1;34;40mIP ADDRESS\033[0m To Login. |
|
# 2. Type \033[1;34;40mP/p\033[0m To Print The Servers You Available. |
|
# 3. Type \033[1;34;40mQ/q\033[0m To Quit. |
|
# \033[1;34;40mOpt or IP>:\033[0m """ |
|
# try: |
|
# conn = MySQLdb.connect(host='%s' % DBHOST ,user='%s' % DBUSER , passwd='%s' % DBPWD , db='%s' % DBNAME , charset='utf8') |
|
# except Exception, e: |
|
# print e |
|
# sys.exit() |
|
# cursor = conn.cursor() |
|
# fout = open (FILENAME , "ab") |
|
# print WELCOME |
|
# while True: |
|
# choice = raw_input( CHOICE ) |
|
# if cmp(choice,"P") == 0 or cmp(choice,"p") == 0 : |
|
# print getServersList() |
|
# elif cmp(choice,"Q") == 0 or cmp(choice,"q") == 0: |
|
# print 'Exit.' |
|
# break |
|
# else: |
|
# sshLogin(choice) |
|
# |
|
# cursor.close() |
|
# conn.close() |
|
# fout.close() |
|
# |
|
# [root@jump1 build]# |