#
使用 File::Find
use File :: Find;
use Time :: Piece;
$timeOneDay = 86400 ;
$dayMultipler = 1 ;
$ByteCount = 0 ;
$fileAll = 0 ;
$fileJpg = 0 ;
$fileYes = 0 ;
$pathToTra = " . " ;
$gt = localtime ;
$t1 = $gt -> epoch;
find( \& fileThumb , $pathToTra );
$gt = localtime ;
$t2 = $gt -> epoch;
print " Total KByte: " . ( $ByteCount / 1024 ) . " \n " ;
print " Total Scan: " . $fileAll . " \n " ;
print " Total Jpeg: " . $fileJpg . " \n " ;
print " Total Match: " . $fileYes . " \n " ;
print " Total TimeCost: " . ( $t2 - $t1 ) . " \n " ;
sub fileThumb
{
$fileAll ++ ;
if (( /.*\. jpg$ / ) )
{
$fileJpg ++ ;
my $lt = 0 ;
$lt = localtime ;
my ( $dev , $ino , $mode , $nlink , $uid , $gid , $rdev , $size , $atime , $mtime , $ctime , $blksize , $blocks ) = stat ( $_ ) or die " Unable to stat $_\n " ;
if ( $mtime < ( $lt -> epoch - $timeOneDay * $dayMultipler ) )
{
print " [ $fileYes ] " . " $File::Find::name " ;
print $size . " " . $ctime . " " . $lt -> epoch . " \n " ;
$ByteCount += $size ;
$fileYes ++ ;
}
}
}
日志
# !/bin/perl
use Encode ;
open (NOTESFILES , $ARGV [ 0 ]);
my %errorMeganotes ;
print " >>>>>>>>>>>>>> " , $ARGV [ 0 ] , " <<<<<<<<<<\n " ;
while ( < NOTESFILES > ) {
if ( $_ =~/^ ( \ d{ 4 } -\ d{ 2 } -\ d{ 2 } \ s \ d{ 2 } :\ d{ 2 } :\ d{ 2 }) \ s + ERROR \ s + ( .* ) \ s / g ){
if ( $errorMeganotes {$ 2 }){
push @{ $errorMeganotes {$ 2 }} , $ 1 ;
} else {
$errorMeganotes {$ 2 } = [$ 1 ];
}
}
}
for ( keys %errorMeganotes ){
my $tmp_keys = $_ ;
my @tmp_array = @{ $errorMeganotes { $tmp_keys }};
print " error number :>> " , scalar ( @tmp_array ) , " <<\n " , encode( " GBK " , decode( " UTF-8 " , $tmp_keys )) , " \n " , join ( " ,\t " , @tmp_array ) , " \n\n\n " ;
}
sh
# !/bin/sh
nowDate = $(date - d ' -1 day ' +% Y -% m -% d);
echo $nowDate
perl / data / apps / shell / meganotesErrorLog.pl / data / apps / meganotes / tomcat / logs / app / app.log.$nowDate > _tmp_$nowDate ;
perl / data / apps / shell / meganotesErrorLog.pl / data / apps / schedule / tomcat / logs / app / app.log.$nowDate >> _tmp_$nowDate ;
mail - s $nowDate - ERROR - log my@mail.com < _tmp_$nowDate;
rm _tmp_$nowDate ;
結果:
>>>>>>>/data/apps/meganotes/tomcat/logs/app/app.log.2009-02-18<<<<<<<<<
error number :>>2<<
MusicActionOpLogProxy:142 - music.popularTime=[Invalid field value for field "music.popularTime".]
2009-02-18 15:53:54, 2009-02-18 16:00:12
。。。。。。
參考:
http://my.huhoo.net/archives/2007/08/perl_1.html
簡單的
echo "tt" |perl -ne 'print $_ '
多行
find . -type f |perl -ne 'print $1 $_ if $_=~ /(.*)flv/'
限定行數
find . -type f |perl -ne 'print $_ if $_=~ /.*flv/ && $tmp++ <10 && $tmp >4'
#當然shell>> find . -type f |grep ".*flv" |sed -n '5,10p' 和上面是一樣的
# 不過 你看那 其中使用 $1 等正則重定向 ,哈哈
結果大體上
./test3/0.flv
./flvplayer.swf
./test.flv
./0.flv
perl -h
-e program one line of program (several -e's allowed, omit programfile)
-n assume "while (<>) { ... }" loop around program
-p assume loop like -n but print line also, like sed
普通的 log4j 日志 ;
當然 特殊要求 特殊處理 。
# !/bin/perl
open (FILES , " /data/apps/schedule/tomcat/logs/app/app.log.2009-02-17 " );
while ( < FILES > ) {
next if !/^\ d{ 4 } -\ d{ 2 } -\ d{ 2 } \ s \ d{ 2 } :\ d{ 2 } :\ d{ 2 } \ s + ERROR \ s +/ ;
if ( $_ =~/ ( .*- ){ 3 }( .*? ) : ( .* )$ / g){
$error {$ 2 } ++ ;
} elsif ( $_ =~/ ( .*- ){ 3 }( .* ) / g ){
$error {$ 2 } ++ ;
}
。。。。。
}
print " $_: $error{$_}\n " for ( keys %error );
java.net.SocketTimeoutException: 4
test1 illegal!: 4
cd illegal!: 4
test2 illegal!: 4
MusicAlbum not exists: 5
Not Found Any File: 14
java.net.ConnectException: 3
Album not exists: 2
。。。
寫 shell 使用 if 留個文
說明:
下面可學習到
1. 當 sh 文件接受到 2個,1個,或無參數時 解決辦法(注意 $1 要 "$1" 這樣使用 )
2. sh 中 參數賦值 _var = $(...)
3. 取得當前時間
$(date + %Y - %m - %d ) 前天時間 $(date -d '-1 day' +%Y-%m-%d)
if [ - n "$ 2" ] ; then
mydate = $ 1
_copyright=/ data / ftp_share / copyright / $ 2 - copyright . 000
_walkman=/ data / ftp_share / copyright / $ 2 - walkman . 000
_fullsong=/ data / ftp_share / copyright / $ 2 - fullsong . 000
_shaker=/ data / ftp_share / copyright / $ 2 - shaker . 000
_color=/ data / ftp_share / copyright / $ 2 - color . 000
elif [ - n "$ 1" ] ;then
mydate = $ 1
_copyright= $(python findIncBizDataFile . py copyright $ 1 )
_walkman = $(python findIncBizDataFile . py walkman $ 1 )
_fullsong = $(python findIncBizDataFile . py fullsong $ 1 )
_shaker = $(python findIncBizDataFile . py shaker $ 1 )
_color = $(python findIncBizDataFile . py color $ 1 )
else
# ydate=$(date -d '-1 day' +%Y-%m-%d)
mydate = $(date + %Y - %m - %d )
_copyright = $(python findIncBizDataFile . py copyright)
_walkman = $(python findIncBizDataFile . py walkman)
_fullsong = $(python findIncBizDataFile . py fullsong)
_shaker = $(python findIncBizDataFile . py shaker)
_color = $(python findIncBizDataFile . py color)
fi;
if 參數說明
–b 當file存在并且是塊文件時返回真
-c 當file存在并且是字符文件時返回真
-d 當pathname存在并且是一個目錄時返回真
-e 當pathname指定的文件或目錄存在時返回真
-f 當file存在并且是正規文件時返回真
-g 當由pathname指定的文件或目錄存在并且設置了SGID位時返回為真
-h 當file存在并且是符號鏈接文件時返回真,該選項在一些老系統上無效
-k 當由pathname指定的文件或目錄存在并且設置了“粘滯”位時返回真
-p 當file存在并且是命令管道時返回為真
-r 當由pathname指定的文件或目錄存在并且可讀時返回為真
-s 當file存在文件大小大于0時返回真
-u 當由pathname指定的文件或目錄存在并且設置了SUID位時返回真
-w 當由pathname指定的文件或目錄存在并且可執行時返回真。一個目錄為了它的內容被訪問必然是可執行的。
-o 當由pathname指定的文件或目錄存在并且被子當前進程的有效用戶ID所指定的用戶擁有時返回真。
UNIX Shell 里面比較字符寫法:
-eq 等于
-ne 不等于
-gt 大于
-lt 小于
-le 小于等于
-ge 大于等于
-z 空串
= 兩個字符相等
!= 兩個字符不等
-n 非空串
在這有個比較郁悶的地方 (
由 )
有那個 能幫我下 if and 使用
比如:
if [ - z ] && [ - z ]; then echo 11 ; else echo 22 ; fi;
結果 11 (正確)
if [ - n 1 ] && [ - n ]; then echo 11 ; else echo 22 ; fi;
結果 11 (錯誤)
這是 不能理解的 地方,
if [ - n 1 ] && [ - n '' ]; then echo 11 ; else echo 22 ; fi;
或
if [ - n 1 ] && [ - n "" ]; then echo 11 ; else echo 22 ; fi;
結果 22 (正確)
應該是 22 但結果是 11 郁悶!!
這個函數,好像有 。net的影子
class C(object):
def __init__ (self): self._x = None
def getx(self): print " get x " ; return self._x
def setx(self, value): print " set x " ; self._x = value
def delx(self): print " del x " ; del self._x
x = property(getx, setx, delx, " I'm the 'x' property. " )
使用
>>> t=C()
>>> t.x
get x
>>> t.x="en"
set x
>>> print t.x
get x
en
>>> del t.x
del x
>>> t.x
get x
我這就拋磚引玉了,大家多指教。
參考:
http://pycurl.sourceforge.net/doc/pycurl.html
如果想多線程下載,請關注下面url
http://groups.google.com/group/python-cn/msg/cdbe671b814fd3af
http://www.pythonclub.org/doku/index.php/python-network-application/pycurl
(個人粗略認為)原理:
把服務器上的文件分n“等份”,再在準備下載地址按等分一一填充到文件中。
當 下載 “等份數據” 時如果未能正常結束,從頭下載次等份數據。正常結束后線程下載下一等分。
好比:
服務器文件(x): 1111111
待填充文件(y): 0000000
運行1:(2分鐘)
文件(x):0101001
接著運行2:(1分鐘,斷點續傳)
文件(x):1111001
最后:文件(x):1111111
需要技術:
1.按切割下載
2.本地創造與服務器文件一樣大小空文件。
2.等份寫入
技術1代碼(按切割下載).
c.setopt(pycurl.RANGE, ' %d-%d ' % ( 500 , 1000 ))
import pycurl
c = pycurl.Curl()
c.setopt(pycurl.URL, " http://www.python.org/ " )
c.setopt(pycurl.HTTPHEADER, [ " Accept: " ])
import StringIO
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.setopt(pycurl.FOLLOWLOCATION, 1 )
c.setopt(pycurl.MAXREDIRS, 5 )
c.setopt(pycurl.RANGE, ' %d-%d ' % ( 500 , 1000 ))
c.perform()
print b.getvalue()
技術2(本地創造與服務器文件一樣大小空文件)
def allocate_space(self):
'''
預分配文件空間(通用?)
'''
afile = file(self.url_info[ ' file ' ], ' wb ' )
afile.truncate(self.url_info[ ' size ' ])#文件大小限定
afile.close()
技術3(等份寫入 file.
seek ):
# ----關鍵----
def write_cb(self, data):
if self.piece:
self.result.seek (self.piece[ 1 ] + self.piece_downloaded, 0)
self.result.write(data)
self.result.flush()
size = len(data)
self.link_downloaded += size
self.piece_downloaded += size
self.total_downloaded += size
if self.is_stop: return - 1
pycurl 學習筆記:
$ftp讀取
import pycurl
tfile = ' ftp://name:pass@218.200.***.***/tongbu/test.txt '
c = pycurl.Curl()
c.setopt(pycurl.URL, tfile)
import StringIO
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.setopt(pycurl.FOLLOWLOCATION, 1 )
c.setopt(pycurl.MAXREDIRS, 5 )
# c.setopt(pycurl.RANGE, '%d-%d' % (2, 6))
c.perform()
print b.getvalue()
下載寫入:
bean_ pycurl= pycurl.Curl()
...
bean_ pycurl .setopt(pycurl.WRITEFUNCTION, write_cb)
...
def write_cb(data):
file.write(data)
..
和網上的相比 ,就是 linux使用
http://www.jython.org/Project/download.html
下載 jython 包,(安裝!不,就直接解壓jar 就可以用了,我 linux 沒有窗口!可憐 )
jar -xvf jython_install.jar
使用 root
vim /etc/profile #添加
export JAVA_HOME =/ usr / local / jdk1. 5 .0_17
export CLASSPATH = .:$JAVA_HOME / lib:$JAVA_HOME / jre / lib: / home / xj_liukaiyi / src / java / lib / ojdbc14 - 1.0 .jar: / home / xj_liukaiyi / src / jython / evn_lib / jython.jar
export PATH = $JAVA_HOME / bin:$JAVA_HOME / jre / bin:$PATH
alias jython = ' java org.python.util.jython '
測試 oracle
# !jython
from oracle.jdbc.driver import OracleDriver
from java.sql import DriverManager
def connect(un = ' dbuser ' , pw = ' pass123 ' , sid = ' ora10g ' , host = ' 192.168.102.223 ' , port = ' 1688 ' ):
driver = OracleDriver()
DriverManager.registerDriver(driver)
connection = " jdbc:oracle:thin:@%s:%s:%s " % (host, port, sid)
return DriverManager.getConnection(connection, un, pw)
def doSelect(strSql,func = None,doConn = None):
is_now_conn = None
if not doConn :
is_now_conn = True
doConn = connect()
stmt = doConn.createStatement()
datas = []
rows = 0
try :
try :
rset = stmt.executeQuery(strSql)
ccount = rset.getMetaData().getColumnCount()
data = []
while (rset.next()):
rows = rows + 1
# print rset.getObject(1)
for ii in range(ccount):
data.append(rset.getObject(ii + 1 ))
if func :
func(data,rows)
datas.append(data)
except :
pass
finally :
try :
stmt.close()
finally :
if is_now_conn :
doConn.close()
print " -conn close- "
return datas
def runRow(data,rows):
print " runRow row=%s data=%s " % (rows,data)
if __name__ == " __main__ " :
# 模式1 定義一次 conn close
# 可插拔式 定義方法使用 runRow (羅嗦下java 要達到只能寫接口 !)
doSelect( ' select count(*) from MN05_TBL_BIZ ' ,runRow )
# 模式2 外部定義 conn 并,可多次使用 后 conn close
conn = connect()
print doSelect( ' select count(*) from MN05_TBL_COPYRIGHT ' ,doConn = conn )
print doSelect( ' select count(*) from MN05_TBL_BIZ ' ,doConn = conn )
from java.lang import *
print tts[ 2 ]
# 梁詠琪 #有換行 這 使用 java.lang.String.trim
#
sql = """
select tb.NAME
from MN05_TBL_BIZ tb , MN05_TBL_COPYRIGHT tc
where
tb.copyright_id=tc.COPYRIGHT_ID and
tb.actor = '%s'
""" % ( String(tts[ 2 ]).trim() )
# 中文匹配問題這 使用 decode('utf8') 變成unicod 就可以了
arr=db.doSelect(sql.decode( ' utf8 ' ) ,doConn= conn)
for t in arr[0]:
print t.encode('utf-8')
conn.close()
jython 結果
-bash-3.00$ jython db.py
runRow row=1 data=[3487033]
-conn close-
[[1563479]]
[[3487033]]
./pyftp_sync.py /tongbu/day/spbusinessinfo/all/$mydate-walkman.000 $mydir$mydate-walkman.000 218.205.XXX.XXX Name Pass123 get >> pyftp_sync.log
# !/usr/bin/python
# -*- coding: utf-8 -*-
import ftplib
import datetime
import os
import sys
import socket
import time
# time access
TF0 = ' %Y-%m-%d-%H:%M:%S '
MAX_RETRY= 60
SLEEP_TIME= 30
#
# 虜脦媒潞
#脦錄鎂鹵戮碌氐脴路
#脦錄鎂ftp目碌牡脴路
#ftp ip
#ftp脫祿摟脙
#ftp脙脗
#
# cal src file path
dpath = sys.argv[ 1 ]
print " [ " + datetime.datetime.now().strftime(TF0) + " ] - " + " dpath= " + dpath
# cal desc file path
spath = sys.argv[ 2 ]
ftp_addr = sys.argv[ 3 ]
ftp_usr = sys.argv[ 4 ]
ftp_pwd = sys.argv[ 5 ]
ftp_method = sys.argv[ 6 ]
print " [ " + datetime.datetime.now().strftime(TF0) + " ] - " + " spath= " + spath
print " [ " + datetime.datetime.now().strftime(TF0) + " ] - " + " ftp= " + ftp_addr + " ,user= " + ftp_usr + " ,pwd= " + ftp_pwd
if ftp_method == ' put ' and os.path.isfile(spath) is False:
print " [ " + datetime.datetime.now().strftime(TF0) + " ] - [ERROR] " + " spath= " + spath + " not exists "
else :
for i in range(MAX_RETRY):
try :
# ftp connection
ftp = ftplib.FTP()
ftp.set_debuglevel( 2 )
ftp.connect(ftp_addr, 21 )
ftp.login(ftp_usr, ftp_pwd)
# ftp.mkd("test1")
if ftp_method == ' put ' :
print " put "
ftp.storbinary(" STOR " + dpath, open(spath))
if ftp_method == ' get ' :
print " get "
# ftp.set_pasv(True);
ftp.retrbinary( " RETR " + dpath, open(spath, ' wb ' ).write)
# ftp.storlines("STOR " + dpath, open(spath))
# check file
sfile_size = os.path.getsize(spath)
print " [%s] - file size=%.3fK " % (datetime.datetime.now().strftime(TF0), sfile_size / 1024 )
dfile_size = ftp.size(dpath)
if sfile_size == dfile_size:
print " [ " + datetime.datetime.now().strftime(TF0) + " ] - " + " send file success "
ftp.quit()
ftp.close()
break
print " [%s] - failed on check: src size.%d != desc size%d " % (datetime.datetime.now().strftime(TF0),sfile_size,dfile_size)
ftp.quit()
ftp.close()
except Exception, myError:
excType, excValue, traceBack = sys.exc_info()
print excType
print myError
# print excValue
# print traceBack
time.sleep(SLEEP_TIME)
下載
http://www.aygfsteel.com/Files/Skynet/turtle.rar
(目前項目什么都沒有
,就是個架子 。有時間會跟新的 ,如果有人想加入,請聯系我 liukaiyi@gmail.com)
由于時間粗略 ,寫的亂。不過想法很好(安全什么叫別說了,定位就是給自己用的)
剛處理 shell <-> py 亂碼問題 ,留文
由于萬惡的Windows dos 使用gbk 編碼 ,導致我連他的 comm 一定要使用 編碼轉換
從頁面接受到到的命令 :
commCharset="GBK"
sh_comm=sh_comm.encode(commCharset)
運行命令得到的結果
fp=os.popen(sh_comm)
sh_comm_value=unicode(fp.read(), commCharset)
你想要的學習筆記本 = web + shell + python + 文本 ;
想法是:通過web 使用shell強大的文本處理功能。幫助你整理學習筆記
比如:
一個py 中文處理你剛解決,到頁面上 隨便輸入 你解決的辦法,貼個關鍵字。
下次
findWords.sh(shell 自己定義,當然可以使用web 包裝下 ) >>
#/bin/shell
find / -type f -name | grep $1
findWords.sh 中文處理
http://www.aygfsteel.com/Files/Skynet/turtle.rar
項目說明 :
項目目前使用 windows + cygWin shell
配置好 django
使用 eclipes + ant (pybuild.xml)
上面的運行只是能簡單在web中的運行shell和展現運行結果
運行結果
shell 命令
ls -l
總計 96
drwxr-xr-x 4 Administrator None 0 Dec 2 14:11 myTurtle
-rw-r--r-- 1 Administrator None 21 Dec 2 14:34 pybuild.properties
-rw-r--r-- 1 Administrator None 1040 Dec 2 14:16 pybuild.xml
drwxr-xr-x 2 Administrator None 0 Dec 2 17:07 shell
-rw-r--r-- 1 Administrator None 164 Dec 2 16:47 需求