Python - tai nhac


from urllib2 import urlopen
import urllib2
import re
import sys
import string
from datetime import datetime
import os
def httpDownloader(out_file, req=None, url=None):
    if req:
        net_stream = urlopen(req)
    elif url:
        net_stream = urlopen(url)
    else:
        return 0
    file_len = int(net_stream.info().getheaders('content-length')[0])
    if os.path.isfile(out_file):
        if os.path.getsize(out_file) == file_len:
            print "%s exists!" % out_file
            return 0
        else:
            print "%s exists but was not fully downloaded!" % out_file
    print "Downloading %s..." % out_file
    out_stream = open (out_file, 'wb')
    try:
        while True:
            bs = 512*8
            block = net_stream.read(bs)
            if not block:
                break
            out_stream.write(block)
    except:
        out_stream.close()
        net_stream.close()
        return 0
    out_stream.close()
    net_stream.close()
    return 1
#########################
#Main program
#########################
if __name__ == '__main__':
    #Destination directory, where folder will be placed
    #dest_dir = "~/Music"
    dest_dir = "/media/Data/Music"
    #url
    #fake the mozilla headers
    hdrs = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; en-US)AppleWebKit/533.2\
            (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2'}
    #get the current month
    dt = datetime.today()
    month = dt.month
    dest_dir = os.path.expanduser(dest_dir)
    sub_dir = string.join(["Thang", str(month)], '')
    #absolute path to destination directory
    if dest_dir[-1] == '/':
        abs_dir = string.join([dest_dir, sub_dir, '/'], '')
    else:
        abs_dir = string.join([dest_dir, '/', sub_dir, '/'], '')
    if not os.path.isdir(abs_dir):
        try:
            os.mkdir(abs_dir)
        except:
            print "Error, Can not create the directory %s" % abs_dir
            sys.exit()
    #make request
    req = urllib2.Request(url, headers=hdrs)
    #create streamreader
    fpage = urlopen(req)
    #regex
    fline = re.compile(r'http://.*dl\.mp3.*\.mp3\"')
    _rem = re.compile(r'\?filename=|\"')
     
     
    links_list = []
    try:
        while True:
            lnk = fpage.readline()
            if not lnk:
                break
            else:
                rlink = fline.search(lnk)
                if rlink:
                    link_and_name = _rem.sub(' ', rlink.group())
                    splitted = link_and_name.split()
                    links_list.append([splitted[0], splitted[1]])
    finally:
        fpage.close()
    count = 0
    try:
        for [link, file_name] in links_list:
            link_req = urllib2.Request(link, headers=hdrs)
            out_file = string.join([abs_dir, file_name], '')
            count = count + httpDownloader(out_file, req=link_req)
    except KeyboardInterrupt:
        print "User pressed Ctrl-C! Quitting..."
        sys.exit(1)
    except :
        print "Something was wrong with links, please check the links!"
         
                                        
                                        
    print "=========================================================="
    print "%d file(s) have/s been downloaded to %s" % (count, abs_dir)
    print "=========================================================="

Chuyển file apk thành file jar

Để chuyển các file apk thành file jar để đọc source code của nó ta dùng dex2jar. Các bạn có thể download dex2jar tại: http://code.google.com/p/dex2jar/downloads/list
Sau khi download về các bạn giải nén ra 1 thư mục. Ví dụ:

Để sử dụng dex2jar, chúng ta sẽ dùng command line như sau: [Đường dẫn đến file dex2jar.bat] [file apk]. Sau đó nhấn Enter.

Sau khi nhấn Enter, thì trên cửa sổ cmd sẽ in ra them một dòng chỉ đến file jar đã được tạo ra từ file apk như hình sau.

Sau khi đã có file jar, ta sẽ dùng chương trình jd-gui để xem toàn bộ source code của file jar. Bạn có thể download jd-gui tại http://java.decompiler.free.fr/?q=jdgui
Các bạn download jd-gui về, giải nén ra và chạy file jd-gui.exe

Chương trình sẽ hiển thị lên. Ta chọn File->Open File để mở file jar mình mới dịch từ file apk lên. Như vậy ta sẽ xem được toàn bộ code và cấu trúc cây thư mục của ứng dụng như sau:


Tra cứu nghĩa tiếng Việt của các từ trong một file văn bản!

import urllib, re, time
textFile = open("E:\LearningProg\Python\english.txt","r")#just a test text file
textDoc = textFile.read()
charset = "[a-zA-Z]+" #set of character for words
words = re.findall(charset,textDoc) #find all word in the text
htmlBody = ""
count = 1
for theWord in words[0:100]:#example with 100 word
wordDict = urllib.urlopen("http://vdict.com/"+theWord.lower()+",1,0,0.html")#open HTML file from vdict.com
wordDictText = wordDict.read()
wordDict.close()
startIndex = wordDictText.find("""<td class="resultContent">""")
temp = wordDictText[startIndex:]
endIndex = temp.find("</td>") + len("</td>")
wordDef = temp[0:endIndex]
print "writing word no.%s" % count
htmlBody += "<p>" + """<h1>""" + str(count) + " --> " + theWord.lower() + """</h1>""" + "</p>"
htmlBody += "<table><tr>" + wordDef + "</tr></table>"
count += 1
if ((count % 5) == 0): time.sleep(60)#sleep for a while after each 5 words waiting vdict.com server
htmlTitle = "<title>" + "Nghia cua cac tu trong " + textFile.name.lower() + "</title>"
htmlCode = "<html>" + htmlTitle + "<body>" + htmlBody + "</body" + "</html>"
fileName = "e:\LearningProg\Python" + "\\" + "TextTest.html"#create a output file in HTML form
outFile = open(fileName,"w")
outFile.write(htmlCode)

outFile.close()

LINUX - Binwalk - firmware analyzer

INSTALLING BINWALK
##################

* Firmware Analyzer, looks for header signatures...

* GET LATEST TAR.GZ AT https://code.google.com/p/binwalk/, I RENAMED MINE TO .TGZ BUT IT DOESNT MATTER AT ALL SINCE TAR.GZ AND TGZ ARE THE SAME FORMAT. THE TAR TOOL WILL STILL EXTRACT IT WITH THE SAME OPTIONS

* NOTE: ITS JUST PYTHON PROGRAM AND ALSO A PYTHON LIBRARY (THAT GETS INSTALLED WITH THE python setup.py install COMMAND)
* THE MAIN PROGRAM THAT STARTS IT IS JUST A PYTHON SCRIPT THAT CAN BE PUT ANYWHERE

* PREQS. Do one by one (do not paste in whole block, literally do one by one)

apt-get update
apt-get -y install subversion 
apt-get -y install build-essential
apt-get -y install mtd-utils 
apt-get -y install zlib1g-dev 
apt-get -y install liblzma-dev 
apt-get -y install gzip 
apt-get -y install bzip2 
apt-get -y install tar
apt-get -y install unrar
apt-get -y install arj 
apt-get -y install p7zip
apt-get -y install openjdk-6-jdk 
apt-get -y install python-magic
apt-get -y install python-matplotlib
mkdir /opt/firmware-mod-kit && chmod a+rwx /opt/firmware-mod-kit
svn checkout http://firmware-mod-kit.googlecode.com/svn/trunk /opt/firmware-mod-kit/trunk
cd /opt/firmware-mod-kit/trunk/src
./configure
make
cd -
 
* TO INSTALL EXTRACT TAR.GZ
mkdir ~/programs
cd ~/programs
wget https://binwalk.googlecode.com/files/binwalk-1.2.1.tar.gz    (note get latest @ https://code.google.com/p/binwalk/ -> download link)
tar -xzvf binwalk-1.2.1.tar.gz
cd binwalk-1.2.1/src
sudo python setup.py install

* NOW TO TEST IT TYPE
binwalk

* IF YOU GET HELP OUT YOU WIN

RUNNING THE BINWALK
###################

* Showing just some main features
* There are lots of ways to extract, so I combine all of the ways into a script

GET PROGRESS WHILE ITS RUNNING
===============================

* Press Enter while its running and it will output progress. You can hold the enter if you want to, but I wouldnt thats just an interruption that slows things down

GET INFORMATION ABOUT HEADERS FROM BINWALK
===========================================

binwalk firmware
binwalk --verbose firmware

ANOTHER INTERSTING OUTPUT
==========================

* Similar to running "strings file" or "od -S file" we can run:
binwalk -S file

EXTRACT OUT THE FILES
===========================================

binwalk -e firmware
binwalk --verbose firmware

* IT MAKES FOLDER: _firmware.extract

HERE ARE ALL THE EXTRACTION OPTIONS
=====================================

* For M, e,r and d You must supply the "e" always
Extraction Options:
        -D, --dd=<type:ext[:cmd]>     Extract <type> signatures, give the files an extension of <ext>, and execute <cmd>
        -e, --extract=[file]          Automatically extract known file types; load rules from file, if specified
        -M, --matryoshka              Recursively scan extracted files, up to 8 levels deep
        -r, --rm                      Cleanup extracted files and zero-size files
        -d, --delay                   Delay file extraction for files with known footers


EXTRACT AND EXTRACT DEEPER AND DEEPER
======================================

* M repeats the options next to it, and it has to come together with at least e

binwalk -Me firmware

* IT MAKES FOLDER: _firmware.extract

MY FAVORITE:
============

binwalk -Me firmware
* IT MAKES FOLDER: _firmware.extract

* AND

binwalk -Mer firmware
* IT MAKES FOLDER: _firmware.extract

HOW TO RUN ALL 7 EXTRACTIONS METHODS
=====================================

* The 7 combos are -Me, -Med, -Mer, -Merd, -e, -ed, -er, -erd in no particular order (remember -e has to be included as its the one that means extraction)


METHOD1: NEW FOLDER NAMES KEEP THE SAME NAME
---------------------------------------------

(FWNAME="random_firmware_file";
binwalk -Me ${FWNAME}; mv _${FWNAME}*extract* _${FWNAME}-Me;
binwalk -Med ${FWNAME}; mv _${FWNAME}*extract* _${FWNAME}-Med;
binwalk -Mer ${FWNAME}; mv _${FWNAME}*extract* _${FWNAME}-Mer;
binwalk -Merd ${FWNAME}; mv _${FWNAME}*extract* _${FWNAME}-Merd;
binwalk -e ${FWNAME}; mv _${FWNAME}*extract* _${FWNAME}-e;
binwalk -ed ${FWNAME}; mv _${FWNAME}*extract* _${FWNAME}-ed;
binwalk -er ${FWNAME}; mv _${FWNAME}*extract* _${FWNAME}-er;
binwalk -erd ${FWNAME}; mv _${FWNAME}*extract* _${FWNAME}-erd;)

METHOD2 (BETTER W/ EXAMPLE) NEW FOLDER NAMES WITH DIFFERENT NAMES
-----------------------------------------------------------------

(FWNAME="random_firmware_file";
NEWNAME="rfw1";
binwalk -Me ${FWNAME}; mv _${FWNAME}*extract* _${NEWNAME}-Me;
binwalk -Med ${FWNAME}; mv _${FWNAME}*extract* _${NEWNAME}-Med;
binwalk -Mer ${FWNAME}; mv _${FWNAME}*extract* _${NEWNAME}-Mer;
binwalk -Merd ${FWNAME}; mv _${FWNAME}*extract* _${NEWNAME}-Merd;
binwalk -e ${FWNAME}; mv _${FWNAME}*extract* _${NEWNAME}-e;
binwalk -ed ${FWNAME}; mv _${FWNAME}*extract* _${NEWNAME}-ed;
binwalk -er ${FWNAME}; mv _${FWNAME}*extract* _${NEWNAME}-er;
binwalk -erd ${FWNAME}; mv _${FWNAME}*extract* _${NEWNAME}-erd;)

---EXAMPLE---

* Extracting Firmware firmware1 using all 7 methods, but renaming new folders to have the name R4223 instead

* THE BEFORE:
cd /somefolder/
ls -lish
* THE BEFORE OUTPUT OF ls -lish:
* total 53M
* 1310776 53M -rw-r--r-- 1 root root 53M Jun 18 09:57 random_firmware_file
du -sh *
* THE BEFORE OUTPUT OF du -sh *:
* 53M     random_firmware_file

THEN RAN THE ABOVE SCRIPT (COPY PASTE IT IN AND HIT ENTER, THE PARENTHESIS ARE GOOD THEY TELL BASH THIS IS ONE GIANT COMMAND, THE ABOVE CAN BE RAN WITHOUT THE PARENTHESIS AS WELL)

* AFTER:
ls -lish
* OUTPUT OF ls -lish:
* total 53M
* 1310776  53M -rw-r--r-- 1 root root  53M Jun 18 09:57 random_firmware_file
* 1310795 4.0K drwxr-xr-x 2 root root 4.0K Jun 18 10:12 _rfw1-e
* 1310814 4.0K drwxr-xr-x 2 root root 4.0K Jun 18 10:13 _rfw1-ed
* 1310833 4.0K drwxr-xr-x 2 root root 4.0K Jun 18 10:13 _rfw1-er
* 1310834 4.0K drwxr-xr-x 2 root root 4.0K Jun 18 10:14 _rfw1-erd
* 1310728 4.0K drwxr-xr-x 4 root root 4.0K Jun 18 10:07 _rfw1-Me
* 1310749 4.0K drwxr-xr-x 4 root root 4.0K Jun 18 10:09 _rfw1-Med
* 1310770 4.0K drwxr-xr-x 4 root root 4.0K Jun 18 10:10 _rfw1-Mer
* 1310783 4.0K drwxr-xr-x 4 root root 4.0K Jun 18 10:11 _rfw1-Merd
du -sh *
* OUTPUT OF du -sh *:
* 53M     random_firmware_file
* 347M    _rfw1-e
* 347M    _rfw1-ed
* 53M     _rfw1-er
* 53M     _rfw1-erd
* 347M    _rfw1-Me
* 347M    _rfw1-Med
* 53M     _rfw1-Mer
* 53M     _rfw1-Merd


SIDE NOTE:
===========

* For the above two examples dont run the scripts or binwalk extractions at the same time on the same firmware name (FWNAME) because they all make the _firmware.extracted folder, so you dont want overwrites happening.

* If your extracting the same firmware using different types of arguments at the same time, make sure your in a different directory, copy the firmware to a different directory. My script doesnt do them at the same time.

Project 1

Programing Project 1
Tổng quát về công việc
Công việc này bao gồm code và kiểm tra 1 chương trình cơ bản chương trình “Hello word” cho bài lab đầu tiên.
Tạo 1 chương trình cơ bản đầu tiên mà bạn xây dựng trng lớp này bao gồm: 1 nhắc nhở cho thông tin, tiếp nhận thông tin, xử lí thông tin rùi hiển thị kết quả lên màn hình.
Nền tảng
Dự án lập trình này là sử dụng các chức năng raw_input và print cùng với 1 số thao tác toán học đơn giản. Một phần qua trọng của dự án là học các kĩ năng cơ bản để truy câp vào website để tải về mô tả dự án và tạo ra chương trình trong python
Kỹ thuật
Chương trình của bạn sẽ nhắc nhở người dùng 2 số nguyên (ko phải thập phân). Và nó sẽ hiển thị kết quả như sau:
- Dòng đầu tiên: tổng 2 số
- Dòng thứ 2 : hiệu 2 số
- Dòng thứ 3: Tích 2 số

- Dòng thứ 4: Thương 2 số, phần còn lại là số dư của 2 số.

http://kevinkien.zz.mu/Python/

key PyCharm

Name: PythonVietNam
Key:
Mã (text):

===== LICENSE BEGIN =====
51673-12042010
00002aNfgswOH0R6o!ZIZA9hFLkokj
!Y5rgu"m2AW4"nYyx0HMyGGSYX"j6x
mQHP3rbgKNW5U0mcaBxZD0if8r!orb
===== LICENSE END =====