顯示具有 Python 標籤的文章。 顯示所有文章
顯示具有 Python 標籤的文章。 顯示所有文章

2012年6月26日 星期二

金山快盤自動簽到 python 3.2

昨天註冊了金山快盤,發現它有每日任務,只要每日簽到就可以增加空間。
有需的拿去用吧。
請自行搭配系統排程。
#! /usr/bin/python 
# -*- coding: utf-8 -*- 
# python 3.2 
import urllib.request 
import http.cookiejar 
import http.cookies 
import platform 
import datetime 
import hashlib 
import json  
import time  
import sys 
import os 
 
class kuaipan: 
    _folder = "/tmp/" 
    _logFile = 'eddie.log' 
    _cookieFile = 'cookie.dat' 
    _login_url = 'https://www.kuaipan.cn/index.php?ac=account&op=login' 
    _sign_url = 'http://www.kuaipan.cn/index.php?ac=common&op=usersign' 
    _logout_url = 'http://www.kuaipan.cn/index.php?ac=account&op=logout' 
 
    _login_data = { 
        'username':'帳號', 
        'userpwd': '密碼' 
    } 
 
    _headers = [ 
        ('host','www.kuaipan.cn'), 
        ('User-Agent','Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.1.8pre) Gecko/20071015 Firefox/2.0.0.7 Navigator/9.0'), 
        ('Referer','http://www.kuaipan.cn/account_login.htm') 
    ] 
 
    _data = { 
        'cookie_file_path':'', 
        'log_file_path':'' 
    } 
     
    _connect_info = {} 
 
    def __init__(self): 
        if platform.system().lower() == 'windows': 
            self._folder = 'C:/' 
 
        self._data['cookie_file_path'] = '{0}{1}'.format(self._folder,self._cookieFile) 
        self._data['log_file_path'] = '{0}{1}'.format(self._folder,self._logFile) 
         
        if not os.path.exists(self._data['log_file_path']): 
            try: 
                with open(self._data['log_file_path'], mode='a', encoding='utf-8') as a_file:                                    
                    a_file.close() 
                self.Log('{0} 檔案不存在已重建'.format(self._data['log_file_path'])) 
            except IOError as ioerr: 
                print(ioerr) 
                sys.exit(1) 
 
        if not os.path.exists(self._data['cookie_file_path']): 
            try: 
                with open(self._data['cookie_file_path'], mode='a', encoding='utf-8') as a_file:                                     
                    a_file.close() 
                self.Log('{0} 檔案不存在已重建'.format(self._data['cookie_file_path'])) 
            except IOError as ioerr: 
                self.Log(ioerr) 
                print(ioerr) 
                sys.exit(1) 
 
        self._connect_info['cookie'] = http.cookiejar.LWPCookieJar() 
 
        try: 
            self._connect_info['cookie'].revert(self._data['cookie_file_path']) 
        except Exception as e:              
            open(self._data['cookie_file_path'], "a") 
        self._connect_info['cookie_processor'] = urllib.request.HTTPCookieProcessor(self._connect_info['cookie']) 
        self._connect_info['post_data'] = urllib.parse.urlencode(self._login_data) 
 
 
    def makeCookie(self, name, value): 
        return http.cookiejar.Cookie( 
            version=0,  
            name = name,  
            value = value, 
            port = None,  
            port_specified=False, 
            domain = self._headers[0][1],  
            domain_specified=True,  
            domain_initial_dot=False, 
            path = "/",  
            path_specified=True, 
            secure=False, 
            expires=None, 
            discard=False, 
            comment=None, 
            comment_url=None, 
            rest={} 
        ) 
 
    def Log(self,msg): 
        try: 
            with open(self._data['log_file_path'], mode='a', encoding='utf-8') as a_file: 
                a_file.write('{0} {1}\n'.format(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f') , msg))                
                a_file.close() 
        except IOError: 
            pass 
 
    def sign(self): 
        conn = urllib.request.build_opener(self._connect_info['cookie_processor']) 
        conn.addheaders = self._headers 
        urllib.request.install_opener(conn) 
        response = conn.open(urllib.request.Request(self._login_url,self._connect_info['post_data'].encode('utf-8'))) 
         
        if response.url != "http://www.kuaipan.cn/home.htm": 
            msgb = '帳號登入錯誤程式終止' 
            self.Log(msg) 
            print(msg)   
            response.close() 
            return False 
 
        response.close() 
        msg = 'kuai %s 登陸成功,準備簽到' % self._login_data['username'] 
        print(msg) 
        self.Log(msg)        
 
        response = conn.open(self._sign_url) 
        sign_js = json.loads(response.read().decode("utf-8")) 
        response.close() 
 
        if sign_js['state'] == -102: 
            msg = 'kuai %s 今天已簽到了' % self._login_data['username'] 
            print(msg) 
            self.Log(msg)  
        elif sign_js['state'] == 1: 
            msg = "簽到成功! 獲得積分:%d,總積分:%d;獲得空間:%dM\n" % (sign_js['increase'], sign_js['status']['points'], sign_js['rewardsize']) 
            print(msg) 
            self.Log(msg) 
        else: 
            msg = 'kuai %s 簽到失敗' % self._login_data['username'] 
            print(msg) 
            self.Log(msg)  
             
        conn.open(self._logout_url)  
        conn.close() 
if __name__ == '__main__': 
    kuaipan().sign() 

2012年5月22日 星期二

AzDG可逆加密演算法 for Python 3.2

遷移到Python 3.2的環境時 AzDG 就動不了,所以得再產出一個3.2版的。

AzDG = AzDG()
 m = AzDG.encode('中文測試')
AzDG.decode(m)
#! /usr/bin/python
# -*- coding: utf-8 -*-
# python 3.2

import hashlib
import base64
import time
import random



class AzDG:
    """docstring for AzDG"""

    __all__ = ["encode", "decode"]

    cipher = '0123456789'
    charset = 'utf-8'
    
    def __init__(self, cipher = None):
        if cipher != None:
            self.cipher = cipher

    def cipherEncode(self, sourceText):    
        cipherHash = hashlib.md5(self.cipher.encode(self.charset)).hexdigest().encode(self.charset)        
        encodeText = bytearray()
        for i in range(len(sourceText)):            
            encodeText.append(sourceText[i] ^ cipherHash[i%32])    
        return encodeText.decode('ISO-8859-1')
                
    def encode(self, sourceText, charset = 'utf-8'):
        if charset != self.charset:
            self.charset = charset
        sourceText = sourceText.encode(self.charset)        
        noise = hashlib.md5(str(time.time()).encode(self.charset)).hexdigest().encode(self.charset)        
        encodeText = bytearray()
        for i in range(len(sourceText)):            
            encodeText.append(noise[i%32])    
            encodeText.append(sourceText[i] ^ noise[i%32])        
        return base64.b64encode(self.cipherEncode(encodeText).encode('ISO-8859-1')).decode(self.charset)
    
    def decode(self, sourceText, charset = 'utf-8'):
        if charset != self.charset:
            self.charset = charset
        decodeSourceText = self.cipherEncode(base64.b64decode(sourceText.encode(self.charset)))        
        textLength = len(decodeSourceText)
        decodeText = bytearray()
        i = 0            
        while i < textLength:    
            decodeText.append(ord(decodeSourceText[i]) ^ ord(decodeSourceText[i+1]))    
            i += 2
        return decodeText.decode(self.charset) 

2012年4月12日 星期四

AzDG可逆加密演算法 for Python


花了二天的時間將AzDG可逆加密演算法改寫成Python
只在Python 2.6版上測試........
另外,針對台灣環境,
進行解密時,若數據源為Big5編碼的字串,會再轉成utf-8的編碼以便正常顯示中文。
#! /usr/bin/python
# -*- coding: utf-8 -*-
# python 2.6

import hashlib
import sys
import base64
import time


default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

class AzDG:
    """docstring for AzDG"""

    cipher = '0123456789'
    charset = 'utf-8'
    
    def __init__(self, cipher = None):
        if cipher != None:
            self.cipher = cipher

    def getCipher(self):
        return self.cipher

    def cipherEncode(self, sourceText):    
        cipherHash = hashlib.md5(self.getCipher()).hexdigest()
        cipherEncodeText = ''
        for i in range(len(sourceText)):            
            cipherEncodeText = '%s%s' % (cipherEncodeText, chr(ord(sourceText[i]) ^ ord(cipherHash[i%32])))    
        print len(cipherEncodeText)    
        return cipherEncodeText

    def encode(self, sourceText, charset = 'utf-8'):
        if charset != self.charset:
            sourceText = sourceText.encode(charset)
        #noise = hashlib.md5('%s' % (time.time())).hexdigest()
        noise = hashlib.md5('%s' % 1).hexdigest()
        encodeText = ''
        for i in range(len(sourceText)):
            encodeText = '%s%s%s' % (encodeText, noise[i%32], chr(ord(sourceText[i]) ^ ord(noise[i%32])))
        return base64.b64encode(self.cipherEncode(encodeText))
    
    def decode(self, sourceText, charset = 'utf-8'):
        decodeSourceText = self.cipherEncode(base64.b64decode(sourceText))
        textLength = len(decodeSourceText)
        decodeText = ''
        i = 0
        while i < textLength:
            decodeText = '{0}{1}'.format(decodeText, chr(ord(decodeSourceText[i]) ^ ord(decodeSourceText[i+1])))
            i = i + 2
        if self.charset != charset:
            decodeText =  unicode(decodeText, charset).encode(self.charset)
        return decodeText   
#utf-8編碼
azdg = AzDG()
m = azdg.encode('中文測試')
print azdg.decode(m)

#big5編碼,下列字串解開後的值︰大5編碼許功蓋中文測試字
print azdg.decode('A6hTbQVgV+wMLlXnVVoOvV0PD/FaCAbqDw8HogLyAfEF7wXlA6lX6VbSVP1Wcw==','big5')



2012年4月10日 星期二

[Python]檔案更新器


最近麻煩同事將要更新的程式碼更新正式機時發現,同事是一行一行的下指令,
例如 ︰
cp -a /tmp/1.php /var/www/html/1.php
cp -a /tmp/2.php /var/www/html/2.php
.....
.......
原因是該主機是新建立的自動更新的Shell還沒寫好,
於是就利用點業餘時間使用Python寫了一隻程式更新器給他使用,
當然這隻程式也可以在Windows底下使用,
當然在Linux下使用後,要確認一下檔案更新後的權限喔。
#! /usr/bin/python
# -*- coding: utf-8 -*-
#

import os
import sys
import array
import errno
import shutil
import platform
def main():
  
    operatFolder = "/tmp"
    declare = '/'
    if len(sys.argv) > 1:
        operatFolder = sys.argv[1]     

    while True:
        iv = raw_input("本次更新檔案的來源資料夾是否為︰[" + operatFolder + "] (y/n/e)︰")
        if iv == "y" or iv == "Y":
            break
        elif iv == "n" or iv == "N":
             while True:
                operatFolder = raw_input("請輸入本次更新檔案的來源資料夾位置︰")              
                if os.path.exists(operatFolder) :
                    break
                else:
                    print "[" + operatFolder + "]資料夾不存在請重新輸入"
        else:
            print "下次再為您服務 byebye!!"
            sys.exit(1) 
    if platform.system().lower() == 'windows':
        declare = '\\'
    filesPath = operatFolder + declare + 'files.txt'
    if not os.path.exists(filesPath):
        print '找不到檔案更新清單︰' + filesPath ,
        sys.exit(1)  
 
    fileopen = open(filesPath)
    failCount = successCount = 0
    failUpfateList = []
    while True:
        line = fileopen.readline().replace(' ','').replace('\n','').replace('\r','').replace('\r\n','')
        if not len(line):
            break
        targetPath = line[:(line.rindex(declare)) + 1]
        fileName = line[(line.rindex(declare)) + 1:]     
        sourcePath = operatFolder + declare + fileName
          
        try:        
            if not os.path.isdir(targetPath):
                print targetPath + '目標資料夾不存在,正在重新建立',
                os.mkdir (targetPath)
                print targetPath + '目標資料夾建立完成',
            shutil.copy2(sourcePath,line)
            if os.path.isfile (line):
                print "[" + line + "] copy success"
                successCount += 1   
        except:
            failUpfateList.append("[" + str(line )+ "]" + str(sys.exc_info()[1]))
            failCount += 1
    fileopen.close()
    print '檔案更新完成,總計︰' + str(successCount + failCount) + ' 成功︰' + str(successCount) + ' 失敗︰' + str(failCount)
    if len(failUpfateList) > 0:
        print "檔案更新失敗清單"
        for element in failUpfateList:
            print element
if __name__ == "__main__":  
    main()
使用的方式
1.先將要更新的程式檔案集中放在同一層的資料夾中。
   Ex
       /tmp
2.將程式檔案於正式機的位徑含檔名寫了 files.txt之中
   Ex
       /var/www/html/1.php
       /var/www/html/2.php
3.下執行命令
 Ex
   python update.py
   或者給update.py執行權限
   ./update.py