這實際上是我本身寫的一些簡單的功能方法,固然有很大一部分代碼是借鑑別人的代碼,新手,寫這個博客只爲python學習階段的積累php
#!/usr/bin/env python # -*- coding: utf-8 -*- ##--------------------------------------------------------------------- ''' 功能:遍歷文件夾,獲得三個列表 參數數量:1 參數列表: s_dir ##文件夾路徑 返回數量:3 返回值列表: filepath_list = [] ##文件長路徑 pathname_list = [] ##路徑 filename_list = [] ##只是文件名 ''' import os def walkDir(s_dir): filepath_list = [] ##文件長路徑 pathname_list = [] ##路徑 filename_list = [] ##只是文件名 for roots,paths,files in os.walk(s_dir): for a in files: filepath_list.append(roots+'/'+a) for p in paths: pathname_list.append(roots+'/'+p) for f in files: filename_list.append(f) return filepath_list,pathname_list,filename_list ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:得到文件md5,注意:不是字符串 參數數量:1 參數列表: strFile ##文件路徑 返回數量:1 返回值列表: strMd5 ##大寫文件md5 ''' import hashlib def getFileMd5(p_strFile): filer = open(p_strFile, "rb") #注意這裏二進制與下面的字符串加密的區別 md5 = hashlib.md5() while True: strRead = filer.read(8096) if not strRead: break md5.update(strRead) strMd5 = md5.hexdigest().upper() filer.close() return strMd5 ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:得到字符串md5,注意:不是文件 參數數量:1 參數列表: p_string ##字符串 返回數量:1 返回值列表: r_md5 ##返回大寫字符串md5 ''' import hashlib def getStringMd5(p_string): #注意這裏字符串與上面二進制加密的區別 r_md5 = hashlib.md5(p_string).hexdigest().upper() return r_md5 ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:base64的加密與解密,sha1,sha256,sha512 參數數量:0 參數列表: 返回數量:0 返回值列表: ''' s = 'wangshiwei' ################################################## import base64 b64 = base64.b64encode(s) print 'b64:\t',b64 deb64 = base64.b64decode(b64) print 'deb64:\t',deb64 ################################################## import hashlib h = hashlib.sha1() h.update(s) sha1 = h.hexdigest() print 'sha1:\t',sha1 ################################################## import hashlib h = hashlib.sha256() h.update(s) sha256 = h.hexdigest() print 'sha256:\t',sha256 ################################################## import hashlib h = hashlib.sha512() h.update(s) sha512 = h.hexdigest() print 'sha512:\t',sha512 ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:得到當前日期和時間 參數數量:0 參數列表: 返回數量:2 返回值列表: day ##日期 now ##時間 ''' import time def getTime(): day = time.strftime("%Y-%m-%d",time.localtime()) now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) return day,now ##==================================================================== ##--------------------------------------------------------------------- ''' 注意:這個要用 # -*- coding: cp936 -*- 功能:解讀.eml文件 參數數量:1 參數列表: emlFileName ##eml文件名 返回數量:2 返回值列表: 若是有附件,就輸出兩個文件,若是沒有就一個說明文檔 使用方法: eml = emailStruct() # 定義結構對象 eml.openAndRead(emlFileName) eml.txtWrite() ''' import email class emailStruct: def __init__(self): self.eSubject = '' # 郵件主題 self.eFromName = '' # 發件人名字 self.eFromAddr = '' # 發件人地址 self.eToAddr = '' # 收件人地址 多是多個地址組合的字符串 用'\n'相隔 self.eTime = '' # 時間 self.eAppendix = '' # 附件名稱 self.eContent = '' # 郵件正文 def openAndRead(self,emlFileName): feml = open(emlFileName, 'r') msg = email.message_from_file(feml) ##此段獲得 郵件主題 subject = msg.get('subject') h = email.Header.Header(subject) dh = email.Header.decode_header(h) ##此處可解析一些編碼 subject = dh[0] self.eSubject = subject[0] ##此段獲得 發件人姓名 和 發件人地址 efrom = email.utils.parseaddr(msg.get('from')) self.eFromName = efrom[0] self.eFromAddr = efrom[1] ##此段獲得 收件人地址 eto = '' for toline in msg.get('to').splitlines(): findst = toline.find('<') if findst == -1: eto = email.utils.parseaddr(msg.get('to'))[1] else: eto = eto + toline[findst:] + '\n' self.eToAddr = eto ##此段獲得 時間 etime = msg.get('date') self.eTime = etime ##循環郵件主體 p = '' for bodycheck in msg.walk(): if not bodycheck.is_multipart(): psname = bodycheck.get_param('name') ##若是是附件 if psname: self.eAppendix = psname psh = email.Header.Header(psname) psdh = email.Header.decode_header(psh) psfname = psdh[0][0] data = bodycheck.get_payload(decode = True) try: f = open(psfname, 'wb') except: f = open('tempps', 'wb') f.write(data) f.close() ##不然是純文本 else: data = bodycheck.get_payload(decode = True) p = p + str(data) self.eContent = p feml.close() ##輸出eml結構的內容 def txtWrite(self): try: ftxt = open('emailInfo.txt', 'w') except IOError: print IOError lines = r'郵件主題:\t' + self.eSubject + '\n' + \ '發件人姓名:\t' + self.eFromName + '\n' + \ '發件人地址:\t' + self.eFromAddr + '\n' + \ '收件人地址:\t' + self.eToAddr + '\n' + \ '日期:\t' + self.eTime + '\n' + \ '附件名:\t' + self.eAppendix + '\n' + \ '正文內容:\t\n' + self.eContent ftxt.write(lines) ftxt.close() ##==================================================================== ##--------------------------------------------------------------------- ''' 注意:接收不到你要調用的函數的返回值 功能:設定時間(就是天天的幾點幾分:24小時制),到點調用你想調用的函數 參數數量:3 參數列表: hour ##時 mi ##分 funName ##函數名 這個是隱藏的 不能直接寫在參數列表裏面 返回數量:0 返回值列表: ''' import time def setTimeTask( hour, mi): while 1: rh=int(time.strftime("%H",time.localtime())) rm=int(time.strftime("%M",time.localtime())) h = int(hour) m = int(mi) if h==rh: if m<=rm: time.sleep(23*3600+(60+m-rm)*60) getStringMd5('wangshiwei') ##你想調用的函數 time.sleep(60) continue else: time.sleep((m-rm)*60) getStringMd5('wangshiwei') ##你想調用的函數 time.sleep(60) continue elif h>rh: tem1=(h-rh-1)*3600+(60-rm+m)*60 time.sleep(tem1) getStringMd5('wangshiwei') ##你想調用的函數 time.sleep(60) continue else: tem2=(23+rh-h)*3600+(60-rm+m)*60 time.sleep(tem2) getStringMd5('wangshiwei') ##你想調用的函數 time.sleep(60) continue ##==================================================================== ##--------------------------------------------------------------------- ''' 注意:接收不到你要調用的函數的返回值 功能:設定時間(就是天天的幾點幾分:24小時制),到點調用你想調用的函數 參數數量:1 參數列表: p_strCommand ##字符串形式的命令 好比:'ping -n 2 -w 1 www.baidu.com' ##ping ip 2次,等待時間爲1s 返回數量:1 返回值列表: redata ##你調用程序的返回值 ''' import subprocess def callExe(p_strCommand): redata = '' try: wdata = subprocess.Popen(p_strCommand, shell=True ,stdout=subprocess.PIPE) redata = wdata.communicate()[0].decode('gb2312') wdata.wait() except Exception,e: redata = e return redata ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:查找給定字符串中的全部 IP 地址 參數數量:1 參數列表: p_strCommand ##字符串 返回數量:1 返回值列表: iplist ##返回一個ip地址的列表 ''' import re def findAllIP(p_strings): iplist = [] p = r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' mo = re.compile(p) m = mo.search(p_strings) if not m: iplist.append('NULL') else: iplist = mo.findall(p_strings) return iplist ##==================================================================== ##--------------------------------------------------------------------- ''' 注意:這是http,不是https 功能:有些網址須要先登陸在下載,好比我想要下載人人相冊,就須要先登陸才能看見相冊,這個根據不一樣網站要抓包分析 參數數量:3 參數列表: url ##你想要下載的url user ##用戶名 password ##密碼 返回數量:1 返回值列表: data ##頁面的html代碼,也多是錯誤信息 ''' import urllib import cookielib import urllib2 def renrenBrowser(url,user,password): #登錄頁面,能夠經過抓包工具分析得到,如finddler,wireshark login_page="http://www.renren.com/PLogin.do" try: #得到一個cookieJar實例,它負責從服務器下載Cookie到本地,而且在發送請求時帶上本地的cookie data = '' cj=cookielib.LWPCookieJar() #cookieJar做爲參數 得到一個opener的實例 opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj),urllib2.HTTPHandler) #假裝成一個正常的瀏覽器,避免有些web服務器拒絕訪問 opener.addheaders=[('User-agent','Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1)')] #生成Post數據,含有登錄用戶名和密碼。 data=urllib.urlencode({"email":user,"password":password}) #以Post的方法訪問登錄頁面,訪問以後cookieJar會自動保存cookie opener.open(login_page,data) #以帶Cookie的方式訪問頁面 op=opener.open(url) #讀取頁面的源碼 data=op.read() ## data.decode('utf-8') return data except Exception,e: print str(e) ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:使用cookie下載網站頁面數據 注意要有http字樣頭,默認超時時間:5秒 參數數量:1 參數列表: url ##你想要下載的url 返回數量:1 返回值列表: data ##頁面的html代碼,也多是錯誤信息 ''' import urllib import cookielib import urllib2 def downloadUrl(url): data = 'NULL' urlPathOne = url cj = cookielib.CookieJar() auth_handler = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(urllib2.HTTPSHandler(),auth_handler,urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) URL_Start = urlPathOne try: handle = urllib2.urlopen(URL_Start,5) data = handle.read() except IOError, e: return e return data ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:使用httpheader模擬瀏覽器下載網頁頁面數據 注意要有http字樣頭,默認超時時間:5秒 參數數量:1 參數列表: url ##你想要下載的url 返回數量:1 返回值列表: data ##頁面的html代碼,也多是錯誤信息,也多是NULL ''' import urllib import cookielib import urllib2 import socket def httpHeader(url): socket.setdefaulttimeout(5) data = 'NULL' try: req_header = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0',\ 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\ 'Accept-Language':'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',\ 'Cookie':'anonymid=hwyz9f6r-ipg7xm; jebe_key=f7c92a91-c7e9-4b69-bdc1-bf5f766b8132%7Ca22b0134bed0e5baa9f32a412aad1b46%7C1403968344919%7C1%7C1403968331677; depovince=JL; _r01_=1; jebecookies=39fccb4d-c041-4891-af90-ab5c553d21c7|||||; ick_login=5449ca00-3317-47c1-b668-c56cca3ab128; _de=37E78EAE52CFD393416FD9B685238F34F4489C1C70DDCBF9; p=ba366aeeaba84cca4169e2c0d286811a1; ap=341251011; first_login_flag=1; t=6f2c8f21365082101c61dbf5f01bb20f1; societyguester=6f2c8f21365082101c61dbf5f01bb20f1; id=341251011; xnsid=1cf75790; loginfrom=null',\ 'Accept-Encoding':'deflate', ##這個地方要注意 不能使壓縮的 \ 'Connection':'keep-alive',\ 'Referer':'http://page.renren.com' ##注意若是依然不能抓取的話,這裏能夠設置抓取網站的host\ } req_timeout = 5 req = urllib2.Request(url,None,req_header) resp = urllib2.urlopen(req,None,req_timeout) data = resp.read() resp.close() return data except Exception,e: return e ##==================================================================== ##--------------------------------------------------------------------- ''' 注意:路徑的斜槓 '/' 功能:ftp下載:指定IP,指定路徑,指定的文件名 這裏是默認密碼,若是有其餘帳戶和密碼,在login中添加 參數數量:3 參數列表: HOST ## IP 或者 域名 DIRN ## 目錄,兩邊不要斜槓 FILE ## 文件名 返回數量:0 返回值列表: 返回的是你想要下載的文件 使用方法: HOST = '10.0.250.251' DIRN = 'disk0/Source/Cases-Analysis/[2012-10-29]CyberUAE' FILE = 'amro.pdf' ''' import ftplib import socket def ftpDownFile(HOST, DIRN, FILE): try : f = ftplib.FTP(HOST) except (socket.error, socket.gaierror), e: print 'ERROR: cannot reach "%s" ' % HOST return print '*** Connected to host "%s" ' % HOST try : f.login() except ftplib.error_perm: print 'ERROR: cannot login anonymously' f.quit() return print '*** Logged in as "anonymous" ' try : f.cwd(DIRN) except ftplib.error_perm: print 'ERROR: cannot CD to "%s" ' % DIRN f.quit() return print '*** Changed to "%s" folder' % DIRN try: file_handler = open(FILE, 'wb') #'RETR %s' %s後面不能有空格 要否則會報錯 沒有這個文件 唉 f.retrbinary('RETR %s' % FILE,file_handler.write) file_handler.close() except ftplib.error_perm: print 'ERROR: cannot read file "%s" ' % FILE file_handler.close() os.unlink(FILE) else: print '*** Downloaded "%s" to CWD' % FILE f.quit() return ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:ftp 鏈接遠程ftp、遍歷某個文件夾返回文件名列表、下載一個文件、關閉ftp 參數數量:太多 參數列表: 太多,應該寫個類,之後再說 返回數量:太多 返回值列表: 使用方法: ftpConnect('10.255.80.42','21','update','123456') aa = getRemoteList('third') downOneFile(aa[0]) ftpClose() ''' import ftplib import socket ftp = ftplib.FTP() def ftpConnect(SrvIP, SrvPort, SrvUser, SrvPass): ftp.set_debuglevel(2) try: ret=ftp.connect(SrvIP, SrvPort) except: str = "220" ftpfind = ret.find(str) if ftpfind == -1: return -1 try: ret = ftp.login(SrvUser, SrvPass) except: ftpfind = ret.find("230") if ftpfind == -1: return -1 ## print ftp.getwelcome() return 0 def getRemoteList(remotepath): remotedir_res = [] filesnum = 0 dirnum = 0 ftp.cwd(remotepath) dir_res = [] ftp.dir('.', dir_res.append) files = [f.split(None, 8)[-1] for f in dir_res if f.find('<DIR>')==-1] for f in files: remotedir_res.append(f) filesnum = filesnum + 1 dirs = [f.split(None, 8)[-1] for f in dir_res if f.find('<DIR>')>=0] for d in dirs: dirnum = dirnum + 1 remotedir_res.append(d) while True: if filesnum < dirnum + filesnum: fa, db=get_dirs_files(remotedir_res[filesnum], filesnum) filesnum = filesnum + fa dirnum = dirnum + db-1 else: break return remotedir_res def downOneFile(filepath): restr = '' try: file_handler = open(filepath,'wb') ftp.retrbinary('RETR %s' % filepath,file_handler.write) ##下載這個文件 file_handler.close() restr = 'success' except Exception,e: restr = str(e) return restr def ftpClose(): ret = ftp.quit() ftpfind = ret.find("221") if ftpfind == -1: print 'Python ftpclose fail' return 0 return 1 ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:複製文件 參數數量:2 參數列表: targetfilepath ##目標文件全路徑 sourcefilepath ##源文件全路徑 返回數量:0 返回值列表: 使用方法: copyFile('ipport.rar','guazai\ipport.rar') ''' def copyFile(targetfilepath, sourcefilepath): source_data = open(sourcefilepath,'rb').read() open(targetfilepath,'wb').write(source_data) ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:檢查目錄是否存在,建立目錄能夠是多層的,檢查文件是否存在 參數數量:2 參數列表: targetfilepath ##目標文件全路徑 sourcefilepath ##源文件全路徑 返回數量:太多 返回值列表: 太多 使用方法: copyFile('ipport.rar','guazai\ipport.rar') makeDir('d:\guazai') checkFile('d:\commonall.py') ''' import os def checkDir(s_dir): if not os.path.isdir(s_dir): return 'no' else: return 'yes' def makeDir(s_dir): try: os.makedirs(s_dir) return 'makedir success' except Exception,e: redata = '' if str(e).find('Error 183')+1: redata = 'already exists\t' return redata + str(e) def checkFile(filePath): if not os.path.isfile(filePath): return 'no' else: return 'yes' ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:鏈接mysql數據庫,同時若是沒有就建立數據庫,關閉鏈接,建立表 參數數量:2 參數列表: targetfilepath ##目標文件全路徑 sourcefilepath ##源文件全路徑 返回數量:0 返回值列表: ''' import MySQLdb class MysqlDBOper: global cnn,cur def cnnsql(): cnn = MySQLdb.connect(host = 'localhost', user = 'wangshiwei', passwd = 'wangshiwei', db = 'dbcryptam') ##若是沒有數據庫dbcryptam 就建立一個,若是有就拉倒 cnn.query('create DATABASE if not exists dbcryptam') cur = cnn.cursor() def cnnclose(): cur.close() cnn.close() def createtable(): ##建表cryptam cur.execute("CREATE TABLE IF NOT EXISTS cryptam(Id INT PRIMARY KEY AUTO_INCREMENT, sha256 VARCHAR(64),SampleDetails LONGTEXT,YaraTags LONGTEXT,Cryptanalysis LONGTEXT,Metadata LONGTEXT,ExternalDynamicResults LONGTEXT,Strings LONGTEXT)") cnn.commit() ## def insertvalue(sha256, SampleDetails, YaraTags, Cryptanalysis, \ ## Metadata, ExternalDynamicResults, Strings): ## sqlstr = "INSERT INTO cryptam(sha256, SampleDetails, YaraTags, Cryptanalysis, Metadata, ExternalDynamicResults, Strings) VALUES('%s','%s','%s','%s','%s','%s','%s')" % (sha256, SampleDetails, YaraTags, Cryptanalysis, Metadata, ExternalDynamicResults, Strings) ## cur.execute(sqlstr) ## ## def updatevalue(SampleDetails): ## sqlstr = "update cryptam set SampleDetails='%s'" % SampleDetails ## cur.execute(sqlstr) ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:測試目的IP的端口的開放狀態 參數數量:2 參數列表: ip ##目標IP port ##端口號,這裏能夠是字符串,也能夠是int型 返回數量:1 返回值列表: flag #打開仍是關閉 ''' import socket def isIPPortOpen(ip,port): flag = '' try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip,int(port))) #注意這裏的參數形式,多了一層括號 s.shutdown(2) flag = 'open' except: flag = 'close' return flag ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:多線程 參數數量:1 參數列表: step ##線程數量,可是調用的另外一個函數時,參數是要在裏面給出的 返回數量:0 返回值列表: ''' import threading import time def startThread(step): threads = [] for port in range(step): t = threading.Thread(target = singleFun, args = ('a','b',)) ##這裏注意多個逗號 threads.append(t) for i in range(len(threads)): time.sleep(0.1) ##延時 若是不適用延時,則幾乎一塊兒開始 threads[i].start() for i in range(len(threads)): threads[i].join() def singleFun(a,b): print a print b print '' ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:得到cmd參數,aa.py a b c d e 分別對應下表0 1 2 3 4 5 參數數量:0 參數列表: 返回數量:1 返回值列表: 返回只返回真正的參數,從a開始的列表 ''' import sys def getArgs(): argarr = [] argarr = sys.argv[1:] return argarr ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:解析html標籤,找到你想要找到的標籤 參數數量:1 參數列表: filename #文件全名 返回數量:太多 返回值列表: 太多,看你想要什麼 ''' from bs4 import BeautifulSoup def htmltag(filename): htmlSourceData = open('5e1b6901604.txt', 'r').read().replace('\n', '') soup = BeautifulSoup(htmlSourceData) tag = soup.html ##print 'tag.head: \n',tag.head ##print 'tag.title: \n',tag.title ##print 'tag.meta: \n', tag.meta ##print 'tag.a: \n', tag.a ##aa = tag.children ##print 'tag.children: \n', aa ##for a in aa: ## print a ## break ##print tag.head.meta ##for i in range(10): ## print soup.contents[i].name ##不理解 ##for child in soup.descendants: ##全部 ## print child ## print '\n' ##for div in tag.find_all('font',color = 'red'): ## print div ##for div in tag.find_all('img', border = 0, width = 552, height = 200): ## print div ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:這不是函數,是整個腳本,測試一段ip中哪些能夠用默認密碼斷定ftp服務是開啓的,爲了提升速度,先ping一下獲得能夠ping通的列表,而後在ftp測試 參數數量:0 參數列表: 返回數量:0 返回值列表: ''' import ftplib import threading def pingip(ip): #每一個ip ping2次,等待時間爲1s output = os.popen('ping -n 2 -w 1 %s' % ip.strip()) return1 = output.read().find('TTL=')+1 if return1: yesiplist.append(ip) def main(HOST): try : f = ftplib.FTP(HOST) f.login() f.quit() print 'OK: %s' % HOST except Exception,e: print e return if __name__ == '__main__': yesiplist = [] threads = [] for i in range(0,256): HOST = '10.0.250.' + str(i) t = threading.Thread(target = pingip, args = (HOST,)) threads.append(t) for th in threads: th.start() for th in threads: th.join() for yil in yesiplist: print yil main(yil) ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:向網站post數據,這個是惡意像某個手機發短信的腳本,利用的是有些網站像手機發送驗證碼 #字樣的須要修改 參數數量:0 參數列表: 返回數量:0 返回值列表: ''' import httplib def postData(): params = " " #body的內容 headers = { "User-Agent": Mozilla/5.0 "(compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)", "Accept": "text/html, */*; q=0.01", "Accept-Language": "en-us", "Content-Type": "application/x-www-form-urlencoded", "Referer": " ", #提交前的頁面 "Host": " "} # con = httplib.HTTPConnection("www.xxx.com") # con.request("POST", "/URI",params,headers) #URI爲提交後的頁面,去掉前面的主機地址 response = con.getresponse() if response.status == 200: 注:這裏的返回代碼並不能說明能成功接收短信 print "Success","\n" else: print "Failed","\n" con.close() ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:對一個字典的value值(int),進行排序 參數數量:1 參數列表: dicName #一個待排序的字典 返回數量:1 返回值列表: sorted_x #排好序的字典序列,注意他是不少字典組成的序列 使用方法: for key in sorted_x: print key[0],str(key[1]) ''' def sortDic(dicName): sorted_x = sorted(dicName.iteritems(),key = lambda asd:asd[1], reverse=True) return sorted_x ##==================================================================== ##--------------------------------------------------------------------- ''' 注意:這裏要使用 # -*- coding: utf-8 -*- 功能:mechanize 模擬提交表單登錄 參數數量:0 參數列表: 這裏根據不一樣需求,想要post的參數個數不一樣,因此能夠把用戶名和密碼換成更多 返回數量:1 返回值列表: htmldata #post以後返回的html數據 使用方法: ''' import mechanize def postForm(): br = mechanize.Browser() br.set_handle_robots(False) # no robots br.set_handle_refresh(False) # can sometimes hang without this br.set_handle_equiv(True) #br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] br.open(r'http://bbs.pediy.com/') formcount=0 for frm in br.forms(): if str(frm.attrs["action"])=="login.php?do=login": break formcount=formcount+1 br.select_form(nr=formcount) control=br.form.find_control('vb_login_username') control.value=r'aaaa' ##用戶名 control=br.form.find_control('vb_login_password') control.value=r'aaaa' ##密碼 response = br.submit() ##提交表單.decode('gbk') htmldata = response.read() if htmldata.find(r'感謝您登陸,紫川。')>-1: print u'登陸成功' else: print u'登陸失敗' return htmldata ##==================================================================== ##--------------------------------------------------------------------- ''' 注意:安裝相應的模塊須要百度本身的雲盤或者下載:http://nchc.dl.sourceforge.net/project/pyhook/pyhook/1.5.1/pyHook-1.5.1.win32-py2.7.exe 第一次運行時,提示沒有pythoncom模塊,就安裝了pywin32,安裝後,能夠正常運行,可是會致使機器髮卡,特別是中斷程序運行後,鼠標會出現一段時間的自由晃動,找了半天緣由,感受主要是事件頻率太高,程序會常常卡在pythoncom.PumpMessages()。 網上搜索了半天,看到有一帖子說是pythoncom.PumpMessages(n),n表示延遲時間,因而試着改了下,發現有必定效果,但不明顯,後來想是否是由於沒有終止程序,纔會致使一直很卡呢,因而添加終止程序語句win32api.PostQuitMessage()。結果還算滿意。 功能:鉤子實現鼠標和鍵盤按鍵事件響應 參數數量:0 參數列表: 返回數量:0 返回值列表: 使用方法: ''' import pythoncom import pyHook import time import threading import win32api def onMouseEvent(event): ## #打開日誌文件 ## file_name = "log/hook_log.txt" ## fobj = open(file_name, 'a') ## ## "處理鼠標事件" ## fobj.writelines('-' * 10 + 'MouseEvent Begin' + '-' * 20 + '\n') ## fobj.writelines("Current Time: %s\n" % time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())) ## fobj.writelines("MessageName: %s\n" % str(event.MessageName)) ## fobj.writelines("Message: %d\n" % event.Message) ## fobj.writelines("Time_sec: %d\n" % event.Time) ## fobj.writelines("Window: %s\n" % str(event.Window)) ## fobj.writelines("WindowName: %s\n" % str(event.WindowName)) ## fobj.writelines("Position: %s\n" % str(event.Position)) ## fobj.writelines('-' * 10 + 'MouseEvent End' + '-' * 20 + '\n') ## ## #關閉日誌文件 ## fobj.close() ## print '%s' % event.MessageName return True def onKeyboardEvent(event): ## #打開日誌文件 ## file_name = "log/hook_log.txt" ## fobj = open(file_name, 'a') ## ## ##"處理鍵盤事件" ## fobj.writelines('-' * 20 + 'Keyboard Begin' + '-' * 20 + '\n') ## fobj.writelines("Current Time:%s\n" % time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())) ## fobj.writelines("MessageName:%s\n" % str(event.MessageName)) ## fobj.writelines("Message:%d\n" % event.Message) ## fobj.writelines("Time:%d\n" % event.Time) ## fobj.writelines("Window:%s\n" % str(event.Window)) ## fobj.writelines("WindowName:%s\n" % str(event.WindowName)) ## fobj.writelines("Ascii_code: %d\n" % event.Ascii) ## fobj.writelines("Ascii_char:%s\n" % chr(event.Ascii)) ## fobj.writelines("Key:%s\n" % str(event.Key)) ## fobj.writelines('-' * 20 + 'Keyboard End' + '-' * 20 + '\n') if str(event.Key)=='F12': #按下F12後終止 wrfile.writelines("Ascii_char:%s\n" %asciistr) wrfile.writelines("Key_char:%s\n" %keystr) wrfile.close() win32api.PostQuitMessage() global keyv keyv = event.Ascii if event.Ascii==27: print 'Esc=======' ## print '%d' % event.Ascii ## #關閉日誌文件 ## fobj.close() return True def loop(a): while(a): time.sleep(1) print str(a) a += 1 global keyv if keyv == 27: break return def hookfun(): #建立hook句柄 hm = pyHook.HookManager() #監控鍵盤 hm.KeyDown = onKeyboardEvent hm.HookKeyboard() #監控鼠標 hm.MouseAll = onMouseEvent hm.HookMouse() #循環獲取消息 pythoncom.PumpMessages(1) if __name__ == "__main__": global keyv keyv = 1 a = 1 ##這裏開兩個線程,由於這樣主線程就不卡了 ##一個參數時候要寫成元組的形式,要否則會報錯:argument after * must be a sequence, not int t = threading.Thread(target = loop, args = (a,)) #這個是監視全局變量的 t2 = threading.Thread(target = hookfun, args = ()) t.start() t2.start() t.join() t2.join() print '-------------------------------------------------------' ##==================================================================== ##--------------------------------------------------------------------- ''' 注意:若是郵箱沒有開啓STMP服務,須要到設置裏面開啓STMP服務,不然會報454,'Authentication' failed, please open smtp flag first這個錯誤 功能:發送郵件 參數數量:太多,本身看 參數列表: 返回數量:太多,本身看 返回值列表: 使用方法: ''' import time import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage def call_sendEmail(): now = time.strftime("%a,%Y-%m-%d %H:%M", time.localtime()) title = u"%s 發送郵件 " % (now) ##這裏注意:連接格式要正確 http://神馬的,還有 若是想法帶有連接的html格式的,要看下面正文處,把plain改爲html content = '<html><h1><a href="http://www.tudou.com" title="假連接" target="_blank" > https://www.baidu.com</a></h1><h2><img src="cid:image1"></h2></html>' ##content = u'woshi羣郵件55555555555 <img src="cid:image1">' ##這裏能夠有多個收件人的,就是說能夠羣發,格式要注意,要弄成array的形式 mail_tolist = ['ccitwsw@sina.com'] #設置服務器,用戶名、口令以及郵箱的後綴 mail_host = "smtp.163.com" mail_postfix = "163.com" dic_user = {'wei522688662@163.com':'wangshiwei'} for d in dic_user: mail_user = d mail_pass = dic_user[d] for mt in mail_tolist: mail_to = mt.strip() return_value = sendEmail( mail_to, title, content, mail_host, mail_user, mail_pass, mail_postfix) if return_value: print "%s %s : 發送成功" % (now,mail_to) else: print "%s %s : 發送失敗" % (now,mail_to) def sendEmail( mail_to, title, content, mail_host, mail_user, mail_pass, mail_postfix): me=mail_user+"<"+mail_user+"@"+mail_postfix+">" msgRoot = MIMEMultipart('related') msgRoot['Subject'] = title msgRoot['From'] = me msgRoot['To'] = mail_to ##正文內容 msgText = MIMEText(content,'plain','utf-8') ##支持中文 ##注意 若是想發送html類型的 ,要把plain改爲html msgRoot.attach(msgText) ## ##正文加個圖片 ## fp = open('D:/python_test/picExif/pic.jpg', 'rb') ## msgImage = MIMEImage(fp.read()) ## fp.close() ## msgImage.add_header('Content-ID', '<image1>') ## msgRoot.attach(msgImage) ## ## ##加個附件 ## att = MIMEText(open('D:/python_test/picExif/pic.jpg', 'rb').read(), 'base64', 'utf-8') ## att["Content-Type"] = 'application/octet-stream' ## att["Content-Disposition"] = 'attachment; filename="pic.jpg"' ## msgRoot.attach(att) try: s = smtplib.SMTP() s.connect(mail_host) ##是否使用ssh 啊不對 好像是tls ## s.ehlo() ## s.starttls() ## s.ehlo() ## s.set_debuglevel(1) s.login(mail_user,mail_pass) s.sendmail(me, mail_to, msgRoot.as_string()) s.close() return True except Exception, e: print str(e) return False ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:把字符串形式的表達式當作正常表達式來求值 參數數量:1 參數列表: 返回數量:1 返回值列表: 返回表達式值或者是錯誤信息 使用方法: print eval('55+22') print calcString('55*22') ''' ##eval函數能夠把一個字符串當作表達式來求值 def calcString(p_str): return eval(p_str) ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:讀取PE文件的數據,你能夠按照它的結構來讀,也能夠按照字節來讀取 參數數量:1 參數列表: filename ##pe文件名 返回數量:0 返回值列表: 使用方法: ''' import os import pefile def readPeFile(filename): ##filename = 'IEBox_fuck.exe' ##斷定pe頭的地址,順便找到入口點 pe = pefile.PE(filename) entrypoint = pe.DOS_HEADER.e_lfanew + 40 if pe.DOS_HEADER.e_magic != 23117: print 'error MZ' if pe.NT_HEADERS.Signature != 17744: print 'error PE' ##讀8個字節,從入口點開始,如下面爲例:一個字節=8bit=4D=M fr = open(filename,'rb') fr.seek(entrypoint) rdata = fr.read(8) ##是這個樣子的 4D 59 07 00 00 10 00 00 ;MY...... fr.close() print len(rdata) fw = open('exe.txt','wb') fw.write(rdata) fw.close() ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 測試方法1:telnet 127.0.0.1 9011 而後輸入一些信息會出現 listener started accept a connect w a n g ('close:', ('127.0.0.1', 54549)) 測試方法2:瀏覽器輸入:127.0.0.1 9011 listener started accept a connectGET /favicon.ico HTTP/1.1 Host: 127.0.0.1:9011 Connection: Keep-Alive User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36 SE 2.X MetaSr 1.0 Accept-Encoding: gzip, deflate 功能:監聽本機端口 參數數量:1 參數列表: port ##端口號 返回數量:0 返回值列表: 使用方法: lst = Listener(9011) # create a listen thread lst.start() # then start ''' import threading import socket encoding = 'utf-8' BUFSIZE = 1024 # a read thread, read data from remote class Reader(threading.Thread): def __init__(self, client): threading.Thread.__init__(self) self.client = client def run(self): while True: data = self.client.recv(BUFSIZE) if(data): string = bytes.decode(data, encoding) print(string) else: break print("close:", self.client.getpeername()) def readline(self): rec = self.inputs.readline() if rec: string = bytes.decode(rec, encoding) if len(string)>2: string = string[0:-2] else: string = ' ' else: string = False return string # a listen thread, listen remote connect # when a remote machine request to connect, it will create a read thread to handle class Listener(threading.Thread): def __init__(self, port): threading.Thread.__init__(self) self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(("0.0.0.0", port)) self.sock.listen(0) def run(self): print("listener started") while True: client, cltadd = self.sock.accept() Reader(client).start() cltadd = cltadd print("accept a connect") lst = Listener(9011) # create a listen thread lst.start() # then start # Now, you can use telnet to test it, the command is "telnet 127.0.0.1 9011" # You also can use web broswer to test, input the address of "http://127.0.0.1:9011" and press Enter button # Enjoy it.... ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:給個ip1和ip2,給出ip1和ip2之間左右的ip,包括邊界 參數數量:2 參數列表: ip1 ## ip2 ##這個比上面的大 返回數量:1 返回值列表: 一個從ip1到ip2的列表 使用方法: bb = rangeIP('10.255.8.49','10.255.9.4') for b in bb: print b ''' def rangeIP(ip1,ip2): temp1 = ip1.strip().split('.') temp2 = ip2.strip().split('.') one1 = int(temp1[0]) one2 = int(temp1[1]) one3 = int(temp1[2]) one4 = int(temp1[3]) two1 = int(temp2[0]) two2 = int(temp2[1]) two3 = int(temp2[2]) two4 = int(temp2[3]) iparr = [] ##ip 就是4位256進制的數 init1 = one1*256*256*256 + one2*256*256 + one3*256 + one4 init2 = two1*256*256*256 + two2*256*256 + two3*256 + two4 for aa in range(init1,init2+1): c1 = aa / (256*256*256) c2 = (aa/(256*256)) % (256) c3 = (aa%(256*256)) / 256 c4 = aa % (256) strip = str(c1) + '.' + str(c2) + '.' + str(c3) + '.' + str(c4) iparr.append(strip) return iparr ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:三個函數,catName,search,findall 參數數量:1 參數列表: p_str ## 待正則查找的字符串 返回數量:1 返回值列表: catName,或者所有字符串,或者一個findall列表 使用方法: g=u"分類: abcdef | 標籤:分類: 0123 | 標籤:" print getRecatName(g) print getReSearch(g) print getReFindAll(g) ''' import re def getRecatName(p_str): bbbb = re.search(u"分類:(?P<catName>.*?)\|", p_str) if(bbbb): catName = bbbb.group("catName") return catName else: return '' def getReSearch(p_str): bbbb = re.search(u"分類:(?P<catName>.*?)\|", p_str) if(bbbb): return bbbb.group(0) else: return '' def getReFindAll(p_str): finda = re.findall(u"分類:(?P<catName>.*?)\|", p_str) if finda: return finda else: return '' ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:在不用層次文件夾中調用某個python文件 參數數量: 參數列表: 返回數量: 返回值列表: 使用方法: ''' ####若是和本文件同一層有個文件名爲:filename.py import filename ####若是和本文件同一層有個文件夾dir,dir裏面有個filename.py import sys sys.path.append('dir') import filename ##若是本文件上面層有個文件filename.py import sys sys.path.append('..') import filename ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:url的編碼和解碼 參數數量: 參數列表: 返回數量: 返回值列表: 使用方法: ''' # -*- coding: utf-8 -*- import urllib ##解碼 encodedUrl = "http%3A%2F%2Fwww.baidu.com%2Fcache%2Fuser%2Fhtml%2Fjump.html" decodedUrl = urllib.unquote(encodedUrl) print "encodedUrl=\t%s\r\ndecodedUrl=\t%s"%(encodedUrl, decodedUrl) ##編碼 decodedUrl = 'http://www.bai du.com/cache/user/html/jump.html' ##一、將空格編碼爲%20 encodeUrl = urllib.quote(decodedUrl) print encodeUrl ##二、將空格編碼爲+加號 這個比較經常使用 encodeUrl = urllib.quote_plus(decodedUrl) print encodeUrl ##==================================================================== ##--------------------------------------------------------------------- ''' 注意:不一樣網站有不一樣的格式,須要抓包 功能:想一個網站 Post數據 參數數量:2 參數列表: url ##post的url pdata ##post的數據,是個字典 返回數量: 返回值列表: 使用方法: ''' import urllib import urllib2 def postx(url, bd): if bd: try: req = urllib2.Request(url, urllib.urlencode(bd)) ##發送的數據是要加密的 u = urllib2.urlopen(req) return u.read() except Exception,e: return str(e) url = 'https://218.203.13.216/api/Submit?marketid=TestUpload&sign=0b65db4cceebb5aca527ab4d3039ca94' bd = {"md5":"7b119bb6058ca8d992f4112ddb64924e","download_url":"http:\/\/test.cn\/test.apk","appname":"\u6d4b\u8bd5\u5e94\u75281","version_name":"2.0.0.1","developer":"test","developer_tel":"0755-88888888","developer_email":"xxxxxxx","app_description":"test1"},{"md5":"5b119bb6058ca8d992f4112ddb649223","download_url":"http:\/\/test.cn\/test2.apk","appname":"\u6d4b\u8bd5\u5e94\u75282","version_name":"2.0.0.2","developer":"test","developer_tel":"0755-88888888","developer_email":"xxxxxxx","app_description":"test2"},{"md5":"5b119bb6058ca8d992f4112ddb649227","download_url":"http:\/\/test.cn\/test2.apk","appname":"\u6d4b\u8bd5\u5e94\u75283","version_name":"2.0.0.3","developer":"test","developer_tel":"0755-88888888","developer_email":"xxxxxxx","app_description":"test3"} a = postx(url, bd) ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:一個模塊的使用,能夠得到不少系統的信息 psutil 參數數量:太多 參數列表: 返回數量: 返回值列表: 使用方法: ''' import psutil import os print os.getpid() print psutil.Process(os.getpid()) eachPro = psutil.Process(1560) eachProName = eachPro.name print eachPro print eachProName plist = psutil.get_process_list() for pl in plist[3:]: print pl ## eachPro = psutil.Process(980) ## eachProName = eachPro.name ## print str(eachProName).lower() ## print eachPro.exe ## aa = eachPro.username; ## print aa ## print eachPro.get_memory_maps() break ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:webPathScan2 掃描一個網站,找到管理員登錄的入口 參數數量:太多 參數列表: 返回數量: 返回值列表: 使用方法: ''' #!/usr/local/bin/python #-*- coding: UTF-8 -*- #QQ29295842 python 網絡安全編程羣 138612676 但願認識更多的朋友 #BLOG http://hi.baidu.com/alalmn import httplib import socket import sys try: print "\t################################################################" print "\t# www.teamopenfire.com #" print "\t# ############### ######## ############ #" print "\t# # # ## ## # # #" print "\t# ###### ###### ## ## # ######## #" print "\t# # # ## ## # # #" print "\t# # # ## ## # ##### #" print "\t# # # ## ## # ##### #" print "\t# # # ## ## # # #" print "\t# # # ## ## # # #" print "\t# ##### [#] ######## [#] ##### AdminFinder #" print "\t# #" print "\t# coded by Ajith KP #" print "\t# Greets to Coded32 and T.O.F members #" print "\t################################################################" var1=0 var2=0 php = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/', 'memberadmin/','administratorlogin/','adm/','admin/account.php','admin/index.php','admin/login.php','admin/admin.php','admin/account.php', 'admin_area/admin.php','admin_area/login.php','siteadmin/login.php','siteadmin/index.php','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html', 'admin_area/index.php','bb-admin/index.php','bb-admin/login.php','bb-admin/admin.php','admin/home.php','admin_area/login.html','admin_area/index.html', 'admin/controlpanel.php','admin.php','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html', 'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html', 'admin/cp.php','cp.php','administrator/index.php','administrator/login.php','nsw/admin/login.php','webadmin/login.php','admin/admin_login.php','admin_login.php', 'administrator/account.php','administrator.php','admin_area/admin.html','pages/admin/admin-login.php','admin/admin-login.php','admin-login.php', 'bb-admin/index.html','bb-admin/login.html','acceso.php','bb-admin/admin.html','admin/home.html','login.php','modelsearch/login.php','moderator.php','moderator/login.php', 'moderator/admin.php','account.php','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.php','admincontrol.php', 'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.php','adminarea/index.html','adminarea/admin.html', 'webadmin.php','webadmin/index.php','webadmin/admin.php','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.php','moderator.html', 'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html', 'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html', 'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.php','account.html','controlpanel.html','admincontrol.html', 'panel-administracion/login.php','wp-login.php','adminLogin.php','admin/adminLogin.php','home.php','admin.php','adminarea/index.php', 'adminarea/admin.php','adminarea/login.php','panel-administracion/index.php','panel-administracion/admin.php','modelsearch/index.php', 'modelsearch/admin.php','admincontrol/login.php','adm/admloginuser.php','admloginuser.php','admin2.php','admin2/login.php','admin2/index.php','usuarios/login.php', 'adm/index.php','adm.php','affiliate.php','adm_auth.php','memberadmin.php','administratorlogin.php'] asp = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/', 'memberadmin/','administratorlogin/','adm/','account.asp','admin/account.asp','admin/index.asp','admin/login.asp','admin/admin.asp', 'admin_area/admin.asp','admin_area/login.asp','admin/account.html','admin/index.html','admin/login.html','admin/admin.html', 'admin_area/admin.html','admin_area/login.html','admin_area/index.html','admin_area/index.asp','bb-admin/index.asp','bb-admin/login.asp','bb-admin/admin.asp', 'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','admin/controlpanel.html','admin.html','admin/cp.html','cp.html', 'administrator/index.html','administrator/login.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html','moderator.html', 'moderator/login.html','moderator/admin.html','account.html','controlpanel.html','admincontrol.html','admin_login.html','panel-administracion/login.html', 'admin/home.asp','admin/controlpanel.asp','admin.asp','pages/admin/admin-login.asp','admin/admin-login.asp','admin-login.asp','admin/cp.asp','cp.asp', 'administrator/account.asp','administrator.asp','acceso.asp','login.asp','modelsearch/login.asp','moderator.asp','moderator/login.asp','administrator/login.asp', 'moderator/admin.asp','controlpanel.asp','admin/account.html','adminpanel.html','webadmin.html','pages/admin/admin-login.html','admin/admin-login.html', 'webadmin/index.html','webadmin/admin.html','webadmin/login.html','user.asp','user.html','admincp/index.asp','admincp/login.asp','admincp/index.html', 'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','adminarea/index.html','adminarea/admin.html','adminarea/login.html', 'panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html','admin/admin_login.html', 'admincontrol/login.html','adm/index.html','adm.html','admincontrol.asp','admin/account.asp','adminpanel.asp','webadmin.asp','webadmin/index.asp', 'webadmin/admin.asp','webadmin/login.asp','admin/admin_login.asp','admin_login.asp','panel-administracion/login.asp','adminLogin.asp', 'admin/adminLogin.asp','home.asp','admin.asp','adminarea/index.asp','adminarea/admin.asp','adminarea/login.asp','admin-login.html', 'panel-administracion/index.asp','panel-administracion/admin.asp','modelsearch/index.asp','modelsearch/admin.asp','administrator/index.asp', 'admincontrol/login.asp','adm/admloginuser.asp','admloginuser.asp','admin2.asp','admin2/login.asp','admin2/index.asp','adm/index.asp', 'adm.asp','affiliate.asp','adm_auth.asp','memberadmin.asp','administratorlogin.asp','siteadmin/login.asp','siteadmin/index.asp','siteadmin/login.html'] cfm = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/', 'memberadmin/','administratorlogin/','adm/','admin/account.cfm','admin/index.cfm','admin/login.cfm','admin/admin.cfm','admin/account.cfm', 'admin_area/admin.cfm','admin_area/login.cfm','siteadmin/login.cfm','siteadmin/index.cfm','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html', 'admin_area/index.cfm','bb-admin/index.cfm','bb-admin/login.cfm','bb-admin/admin.cfm','admin/home.cfm','admin_area/login.html','admin_area/index.html', 'admin/controlpanel.cfm','admin.cfm','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html', 'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html', 'admin/cp.cfm','cp.cfm','administrator/index.cfm','administrator/login.cfm','nsw/admin/login.cfm','webadmin/login.cfm','admin/admin_login.cfm','admin_login.cfm', 'administrator/account.cfm','administrator.cfm','admin_area/admin.html','pages/admin/admin-login.cfm','admin/admin-login.cfm','admin-login.cfm', 'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','login.cfm','modelsearch/login.cfm','moderator.cfm','moderator/login.cfm', 'moderator/admin.cfm','account.cfm','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.cfm','admincontrol.cfm', 'admin/adminLogin.html','acceso.cfm','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.cfm','adminarea/index.html','adminarea/admin.html', 'webadmin.cfm','webadmin/index.cfm','webadmin/admin.cfm','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.cfm','moderator.html', 'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html', 'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html', 'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.cfm','account.html','controlpanel.html','admincontrol.html', 'panel-administracion/login.cfm','wp-login.cfm','adminLogin.cfm','admin/adminLogin.cfm','home.cfm','admin.cfm','adminarea/index.cfm', 'adminarea/admin.cfm','adminarea/login.cfm','panel-administracion/index.cfm','panel-administracion/admin.cfm','modelsearch/index.cfm', 'modelsearch/admin.cfm','admincontrol/login.cfm','adm/admloginuser.cfm','admloginuser.cfm','admin2.cfm','admin2/login.cfm','admin2/index.cfm','usuarios/login.cfm', 'adm/index.cfm','adm.cfm','affiliate.cfm','adm_auth.cfm','memberadmin.cfm','administratorlogin.cfm'] js = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/', 'memberadmin/','administratorlogin/','adm/','admin/account.js','admin/index.js','admin/login.js','admin/admin.js','admin/account.js', 'admin_area/admin.js','admin_area/login.js','siteadmin/login.js','siteadmin/index.js','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html', 'admin_area/index.js','bb-admin/index.js','bb-admin/login.js','bb-admin/admin.js','admin/home.js','admin_area/login.html','admin_area/index.html', 'admin/controlpanel.js','admin.js','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html', 'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html', 'admin/cp.js','cp.js','administrator/index.js','administrator/login.js','nsw/admin/login.js','webadmin/login.js','admin/admin_login.js','admin_login.js', 'administrator/account.js','administrator.js','admin_area/admin.html','pages/admin/admin-login.js','admin/admin-login.js','admin-login.js', 'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','login.js','modelsearch/login.js','moderator.js','moderator/login.js', 'moderator/admin.js','account.js','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.js','admincontrol.js', 'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.js','adminarea/index.html','adminarea/admin.html', 'webadmin.js','webadmin/index.js','acceso.js','webadmin/admin.js','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.js','moderator.html', 'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html', 'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html', 'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.js','account.html','controlpanel.html','admincontrol.html', 'panel-administracion/login.js','wp-login.js','adminLogin.js','admin/adminLogin.js','home.js','admin.js','adminarea/index.js', 'adminarea/admin.js','adminarea/login.js','panel-administracion/index.js','panel-administracion/admin.js','modelsearch/index.js', 'modelsearch/admin.js','admincontrol/login.js','adm/admloginuser.js','admloginuser.js','admin2.js','admin2/login.js','admin2/index.js','usuarios/login.js', 'adm/index.js','adm.js','affiliate.js','adm_auth.js','memberadmin.js','administratorlogin.js'] cgi = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/', 'memberadmin/','administratorlogin/','adm/','admin/account.cgi','admin/index.cgi','admin/login.cgi','admin/admin.cgi','admin/account.cgi', 'admin_area/admin.cgi','admin_area/login.cgi','siteadmin/login.cgi','siteadmin/index.cgi','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html', 'admin_area/index.cgi','bb-admin/index.cgi','bb-admin/login.cgi','bb-admin/admin.cgi','admin/home.cgi','admin_area/login.html','admin_area/index.html', 'admin/controlpanel.cgi','admin.cgi','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html', 'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html', 'admin/cp.cgi','cp.cgi','administrator/index.cgi','administrator/login.cgi','nsw/admin/login.cgi','webadmin/login.cgi','admin/admin_login.cgi','admin_login.cgi', 'administrator/account.cgi','administrator.cgi','admin_area/admin.html','pages/admin/admin-login.cgi','admin/admin-login.cgi','admin-login.cgi', 'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','login.cgi','modelsearch/login.cgi','moderator.cgi','moderator/login.cgi', 'moderator/admin.cgi','account.cgi','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.cgi','admincontrol.cgi', 'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.cgi','adminarea/index.html','adminarea/admin.html', 'webadmin.cgi','webadmin/index.cgi','acceso.cgi','webadmin/admin.cgi','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.cgi','moderator.html', 'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html', 'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html', 'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.cgi','account.html','controlpanel.html','admincontrol.html', 'panel-administracion/login.cgi','wp-login.cgi','adminLogin.cgi','admin/adminLogin.cgi','home.cgi','admin.cgi','adminarea/index.cgi', 'adminarea/admin.cgi','adminarea/login.cgi','panel-administracion/index.cgi','panel-administracion/admin.cgi','modelsearch/index.cgi', 'modelsearch/admin.cgi','admincontrol/login.cgi','adm/admloginuser.cgi','admloginuser.cgi','admin2.cgi','admin2/login.cgi','admin2/index.cgi','usuarios/login.cgi', 'adm/index.cgi','adm.cgi','affiliate.cgi','adm_auth.cgi','memberadmin.cgi','administratorlogin.cgi'] brf = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/', 'memberadmin/','administratorlogin/','adm/','admin/account.brf','admin/index.brf','admin/login.brf','admin/admin.brf','admin/account.brf', 'admin_area/admin.brf','admin_area/login.brf','siteadmin/login.brf','siteadmin/index.brf','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html', 'admin_area/index.brf','bb-admin/index.brf','bb-admin/login.brf','bb-admin/admin.brf','admin/home.brf','admin_area/login.html','admin_area/index.html', 'admin/controlpanel.brf','admin.brf','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html', 'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html', 'admin/cp.brf','cp.brf','administrator/index.brf','administrator/login.brf','nsw/admin/login.brf','webadmin/login.brfbrf','admin/admin_login.brf','admin_login.brf', 'administrator/account.brf','administrator.brf','acceso.brf','admin_area/admin.html','pages/admin/admin-login.brf','admin/admin-login.brf','admin-login.brf', 'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','login.brf','modelsearch/login.brf','moderator.brf','moderator/login.brf', 'moderator/admin.brf','account.brf','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.brf','admincontrol.brf', 'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.brf','adminarea/index.html','adminarea/admin.html', 'webadmin.brf','webadmin/index.brf','webadmin/admin.brf','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.brf','moderator.html', 'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html', 'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html', 'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.brf','account.html','controlpanel.html','admincontrol.html', 'panel-administracion/login.brf','wp-login.brf','adminLogin.brf','admin/adminLogin.brf','home.brf','admin.brf','adminarea/index.brf', 'adminarea/admin.brf','adminarea/login.brf','panel-administracion/index.brf','panel-administracion/admin.brf','modelsearch/index.brf', 'modelsearch/admin.brf','admincontrol/login.brf','adm/admloginuser.brf','admloginuser.brf','admin2.brf','admin2/login.brf','admin2/index.brf','usuarios/login.brf', 'adm/index.brf','adm.brf','affiliate.brf','adm_auth.brf','memberadmin.brf','administratorlogin.brf'] try: site = raw_input("Web Site for Scan?: ") site = site.replace("http://","") ## site = "www.hljclgl.com" print ("\tChecking website " + site + "...") conn = httplib.HTTPConnection(site) conn.connect() print "\t[$] Yes... Server is Online." except (httplib.HTTPResponse, socket.error) as Exit: raw_input("\t [!] Oops Error occured, Server offline or invalid URL") exit() print "Enter site source code:" print "1 PHP" print "2 ASP" print "3 CFM" print "4 JS" print "5 CGI" print "6 BRF" print "\nPress 1 and 'Enter key' for Select PHP\n" code=input("> ") if code==1: print("\t [+] Scanning " + site + "...\n\n") for admin in php: admin = admin.replace("\n","") admin = "/" + admin host = site + admin print ("\t [#] Checking " + host + "...") connection = httplib.HTTPConnection(site) connection.request("GET",admin) response = connection.getresponse() var2 = var2 + 1 if response.status == 200: var1 = var1 + 1 print "%s %s" % ( "\n\n>>>" + host, "Admin page found!") raw_input("Press enter to continue scanning.\n") elif response.status == 404: var2 = var2 elif response.status == 302: print "%s %s" % ("\n>>>" + host, "Possible admin page (302 - Redirect)") else: print "%s %s %s" % (host, " Interesting response:", response.status) connection.close() print("\n\nCompleted \n") print var1, " Admin pages found" print var2, " total pages scanned" raw_input("[/] The Game Over; Press Enter to Exit") if code==2: print("\t [+] Scanning " + site + "...\n\n") for admin in asp: admin = admin.replace("\n","") admin = "/" + admin host = site + admin print ("\t [#] Checking " + host + "...") connection = httplib.HTTPConnection(site) connection.request("GET",admin) response = connection.getresponse() var2 = var2 + 1 if response.status == 200: var1 = var1 + 1 print "%s %s" % ( "\n\n>>>" + host, "Admin page found!") raw_input("Press enter to continue scanning.\n") elif response.status == 404: var2 = var2 elif response.status == 302: print "%s %s" % ("\n>>>" + host, "Possible admin page (302 - Redirect)") else: print "%s %s %s" % (host, " Interesting response:", response.status) connection.close() print("\n\nCompleted \n") print var1, " Admin pages found" print var2, " total pages scanned" raw_input("The Game Over; Press Enter to Exit") if code==3: print("\t [+] Scanning " + site + "...\n\n") for admin in cfm: admin = admin.replace("\n","") admin = "/" + admin host = site + admin print ("\t [#] Checking " + host + "...") connection = httplib.HTTPConnection(site) connection.request("GET",admin) response = connection.getresponse() var2 = var2 + 1 if response.status == 200: var1 = var1 + 1 print "%s %s" % ( "\n\n>>>" + host, "Admin page found!") raw_input("Press enter to continue scanning.\n") elif response.status == 404: var2 = var2 elif response.status == 302: print "%s %s" % ("\n>>>" + host, "Possible admin page (302 - Redirect)") else: print "%s %s %s" % (host, " Interesting response:", response.status) connection.close() print("\n\nCompleted \n") print var1, " Admin pages found" print var2, " total pages scanned" raw_input("The Game Over; Press Enter to Exit") if code==4: print("\t [+] Scanning " + site + "...\n\n") for admin in js: admin = admin.replace("\n","") admin = "/" + admin host = site + admin print ("\t [#] Checking " + host + "...") connection = httplib.HTTPConnection(site) connection.request("GET",admin) response = connection.getresponse() var2 = var2 + 1 if response.status == 200: var1 = var1 + 1 print "%s %s" % ( "\n\n>>>" + host, "Admin page found!") raw_input("Press enter to continue scanning.\n") elif response.status == 404: var2 = var2 elif response.status == 302: print "%s %s" % ("\n>>>" + host, "Possible admin page (302 - Redirect)") else: print "%s %s %s" % (host, " Interesting response:", response.status) connection.close() print("\n\nCompleted \n") print var1, " Admin pages found" print var2, " total pages scanned" raw_input("The Game Over; Press Enter to Exit") if code==5: print("\t [+] Scanning " + site + "...\n\n") for admin in cgi: admin = admin.replace("\n","") admin = "/" + admin host = site + admin print ("\t [#] Checking " + host + "...") connection = httplib.HTTPConnection(site) connection.request("GET",admin) response = connection.getresponse() var2 = var2 + 1 if response.status == 200: var1 = var1 + 1 print "%s %s" % ( "\n\n>>>" + host, "Admin page found!") raw_input("Press enter to continue scanning.\n") elif response.status == 404: var2 = var2 elif response.status == 302: print "%s %s" % ("\n>>>" + host, "Possible admin page (302 - Redirect)") else: print "%s %s %s" % (host, " Interesting response:", response.status) connection.close() print("\n\nCompleted \n") print var1, " Admin pages found" print var2, " total pages scanned" raw_input("The Game Over; Press Enter to Exit") if code==6: print("\t [+] Scanning " + site + "...\n\n") for admin in brf: admin = admin.replace("\n","") admin = "/" + admin host = site + admin print ("\t [#] Checking " + host + "...") connection = httplib.HTTPConnection(site) connection.request("GET",admin) response = connection.getresponse() var2 = var2 + 1 if response.status == 200: var1 = var1 + 1 print "%s %s" % ( "\n\n>>>" + host, "Admin page found!") raw_input("Press enter to continue scanning.\n") elif response.status == 404: var2 = var2 elif response.status == 302: print "%s %s" % ("\n>>>" + host, "Possible admin page (302 - Redirect)") else: print "%s %s %s" % (host, " Interesting response:", response.status) connection.close() print("\n\nCompleted \n") print var1, " Admin pages found" print var2, " total pages scanned" raw_input("The Game Over; Press Enter to Exit") except (httplib.HTTPResponse, socket.error): print "\n\t[!] Session Cancelled; Error occured. Check internet settings" except (KeyboardInterrupt, SystemExit): print "\n\t[!] Session cancelled" ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:office word 文件的操做 參數數量:太多 參數列表: 返回數量: 返回值列表: 使用方法: ''' # -*- coding: utf-8 -*- import win32com from win32com.client import Dispatch, constants w = win32com.client.Dispatch('word.Application') # 或者使用下面的方法,使用啓動獨立的進程: # w = win32com.client.DispatchEx('Word.Application') # 後臺運行,不顯示,不警告 w.Visible = 0 w.DisplayAlerts = 0 # 打開新的文件 doc = w.Documents.Open( FileName = u'D:\\python_test\\win32com\\aaaa.txt' ) # worddoc = w.Documents.Add() # 建立新的文檔 # 插入文字 myRange = doc.Range(0,0) myRange.InsertBefore('aaaaaaaaaaaaaaaaaaaaaa') ##print help(win32com.client) # 使用樣式 wordSel = myRange.Select() wordSel.Style = constants.wdStyleHeading1 ## ### 正文文字替換 ##w.Selection.Find.ClearFormatting() ##w.Selection.Find.Replacement.ClearFormatting() ##w.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 2) ## ### 頁眉文字替換 ##w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting() ##w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting() ##w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute(OldStr, False, False, False, False, False, True, 1, False, NewStr, 2) ## ### 表格操做 ##doc.Tables[0].Rows[0].Cells[0].Range.Text ='123123' ##worddoc.Tables[0].Rows.Add() # 增長一行 ## ### 轉換爲html ##wc = win32com.client.constants ##w.ActiveDocument.WebOptions.RelyOnCSS = 1 ##w.ActiveDocument.WebOptions.OptimizeForBrowser = 1 ##w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4 ##w.ActiveDocument.WebOptions.OrganizeInFolder = 0 ##w.ActiveDocument.WebOptions.UseLongFileNames = 1 ##w.ActiveDocument.WebOptions.RelyOnVML = 0 ##w.ActiveDocument.WebOptions.AllowPNG = 1 ##w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML ) ## ### 打印 ##doc.PrintOut() # 關閉 doc.Close() ##w.Documents.Close(w.wdDoNotSaveChanges) w.Quit() ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:office excel 文件的讀操做 參數數量:太多 參數列表: 返回數量: 返回值列表: 使用方法: ''' # -*- coding: utf-8 -*- ##from pyExcelerator import * ## ##sheets = parse_xls('mini.xls') ##print sheets ##print help(sheets) ##download:http://www.lexicon.net/sjmachin/xlrd.htm import xlrd fname = "mini.xls" bk = xlrd.open_workbook(fname) ##print type(bk) ##print help(bk) shxrange = range(bk.nsheets) try: sh = bk.sheet_by_index(0) except: print "no sheet in %s named Sheet1" % fname nrows = sh.nrows ncols = sh.ncols print "nrows %d, ncols %d" % (nrows,ncols) ##這個下標是從0開始的 ##cell_value = sh.cell_value(6,0) ##print cell_value ##print help(cell_value) ##aa = u'隨碟附送' ##print str(cell_value) ##print str(aa) row_list = [] line = '' col = '' ##print sh.row_values(0) for i in range(nrows): row_data = sh.row_values(i) row_list.append(row_data) line = '' for rd in row_data: if rd == '': rd = 'null' ##注意 這裏處理一下float和字符串輸出的區別 try: line += rd + '\t' except: line += str(rd) + '\t' col += line + '\n' print col ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:office excel 文件的寫操做 參數數量:太多 參數列表: 返回數量: 返回值列表: 使用方法: ''' # -*- coding: utf-8 -*- from pyExcelerator import * ##生成一個工做薄 w = Workbook() ##加入一個Sheet ws = w.add_sheet('Hey, Dude') ws2 = w.add_sheet(u'我是第二個sheet') Titles="省份 開機報活 安裝報活 使用報活 卸載報活 使用次數 安裝次數 win98 win2000 winXP win2003 winVista win7 win2008".split(" ") ##字體 font0 = Font() font0.name = u'宋體' font0.struck_out = True font0.bold = True style0 = XFStyle() style0.font = font0 print help(style0.font) ##單元格邊框 font1 = Font() font1.name = u'幼圓' borders = Borders() borders.left = 5 style = XFStyle() style.borders = borders style.font = font1 ceii=0 for Title in Titles: ws.write(0,ceii,Title.decode('utf-8'),style0) #須要轉中文轉化 ws.write(1,ceii,Title.decode('utf-8'),style) #須要轉中文轉化 ws.write(行、列、內容,樣式) ceii=ceii+1 ## w.save('mini'+str(ceii)+'.xls') ##保存 w.save('mini.xls') ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:多IP代理的請求網站 參數數量:太多 參數列表: 返回數量: 返回值列表: 使用方法: ''' import urllib def url_proxies(): proxylist = ( '211.167.112.14:80', '210.32.34.115:8080', '115.47.8.39:80', '211.151.181.41:80', '219.239.26.23:80', '211.167.112.14:80', '210.32.34.115:8080', '115.47.8.39:80', '211.151.181.41:80', '219.239.26.23:80', '219.157.200.18:3128', '219.159.105.180:8080', '1.63.18.22:8080', '221.179.173.170:8080', '125.39.66.153:80', '125.39.66.151:80', '61.152.108.187:80', '222.217.99.153:9000', '125.39.66.146:80', '120.132.132.119:8080', '119.7.221.137:82', '117.41.182.188:8080', '202.116.160.89:80', '221.7.145.42:8080', '211.142.236.131:80', '119.7.221.136:80', '211.151.181.41:80', '125.39.66.131:80', '120.132.132.119:8080', '112.5.254.30:80', '106.3.98.82:80', '119.4.250.105:80', '123.235.12.118:8080', '124.240.187.79:80', '182.48.107.219:9000', '122.72.2.180:8080', '119.254.90.18:8080', '124.240.187.80:83', '110.153.9.250:80', '202.202.1.189:80', '58.67.147.205:8080', '111.161.30.228:80', '122.72.76.130:80', '122.72.2.180:80', '202.112.113.7:80', '218.108.85.59:81', '211.144.72.154:80', '119.254.88.53:8080', '121.14.145.132:82', '114.80.149.183:80', '111.161.30.239:80', '182.48.107.219:9000', '122.72.0.28:80', '125.39.68.131:80', '118.244.190.6:80', '120.132.132.119:88', '211.167.112.15:82', '221.2.80.126:8888', '219.137.229.214:3128', '125.39.66.131:80', '61.181.22.157:80', '115.25.216.6:80', '119.7.221.137:82', '221.195.42.195:8080', '119.254.88.53:8080', '219.150.254.158:8080', '113.9.163.101:8080', '222.89.154.14:9000', '114.141.162.53:8080', '218.5.74.199:3128', '61.152.108.187:80', '218.76.159.133:80', '59.34.57.88:8080', '118.244.190.34:80', '59.172.208.189:8080', '116.236.216.116:8080', '111.161.30.233:80', '220.248.237.234:8080', '121.14.145.132:82', '202.114.205.125:8080', ) for proxy in proxylist: proxies = {'': proxy} opener = urllib.FancyURLopener(proxies) f = opener.open("http://www.dianping.com/shanghai") print f.read() ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:多個user agents代理的請求網站 http header httpheader 參數數量:太多 參數列表: 返回數量: 返回值列表: 使用方法: ''' #設置多個user_agents,防止百度限制IP user_agents = ['Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20130406 Firefox/23.0', \ 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0', \ 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533+ \ (KHTML, like Gecko) Element Browser 5.0', \ 'IBM WebExplorer /v0.94', 'Galaxy/1.0 [en] (Mac OS X 10.5.6; U; en)', \ 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)', \ 'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14', \ 'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) \ Version/6.0 Mobile/10A5355d Safari/8536.25', \ 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) \ Chrome/28.0.1468.0 Safari/537.36', \ 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; TheWorld)'] for i in range(10): try: domain=urllib2.Request(url) r=random.randint(0,11) domain.add_header('User-agent', user_agents[r]) domain.add_header('connection','keep-alive') response=urllib2.urlopen(domain) uri=response.geturl() print uri except: continue ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:關於鼠標的控制,須要安裝pywin32 得到鼠標位置,設置鼠標位置,點擊鼠標的左右鍵 參數數量:太多 參數列表: 返回數量: 返回值列表: 使用方法: ''' import ctypes def setMousePos(x,y): aa = ctypes.windll.user32 aa.SetCursorPos(x,y) import win32gui def getMousePos(): bb = win32gui.GetCursorPos() return bb import win32api import win32con import ctypes import time def leftMouseClick(x,y): win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y) time.sleep(0.05) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y) def rightMouseClick(x,y): win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN,x,y) time.sleep(0.05) win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP,x,y) ##下面的是鼠標事件捕獲 --未測試 import win32con import win32gui import ctypes from ctypes import wintypes # container class for global hook # this will store the HHOOK id and mouse information class Hook: def __init__(self): self.hook = 0 self.m_struct = None class MSLLHOOKSTRUCT(ctypes.Structure): _fields_ = [("pt", wintypes.POINT), ("mouseData", ctypes.c_long), ("flags", ctypes.c_long), ("time", ctypes.c_long), ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong) )] def CopyMemory( Destination, Source ): Source = ctypes.c_void_p(Source) ctypes.windll.kernel32.RtlMoveMemory(ctypes.addressof(Destination), Source, ctypes.sizeof(Destination)) def PostQuitMessage( nMsg ): return ctypes.windll.user32.PostQuitMessage(nMsg) def GetModuleHandle( lpModuleName ): return ctypes.windll.kernel32.GetModuleHandleA(lpModuleName) def CallNextHookEx( hhk, nCode, wParam, lParam ): return ctypes.windll.user32.CallNextHookEx(hhk, nCode, wParam, lParam) def SetWindowsHookEx( idHook, lpFunc, hMod, dwThreadId ): WINFUNC = ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_long, ctypes.c_long, ctypes.c_long) return ctypes.windll.user32.SetWindowsHookExA( idHook, WINFUNC(lpFunc), hMod, dwThreadId) def UnhookWindowsHookEx( hhk ): return ctypes.windll.user32.UnhookWindowsHookEx(hhk) # create instance of global mouse hook class mll_hook = Hook() mll_hook.m_struct = MSLLHOOKSTRUCT() # mouse hook callback. intercept mouse events def LowLevelMouseProc( nCode, wParam, lParam ): if nCode == win32con.HC_ACTION: # lparam holds the starting address of the mouse hook structure # call copymemory so that m_struct class points to the mouse structure pool CopyMemory( mll_hook.m_struct, lParam ) # print out the cursors x and y screen position if wParam == win32con.WM_MBUTTONUP: PostQuitMessage(0) if wParam == win32con.WM_LBUTTONUP: # WM_RBUTTONUP print "x = [%d]/ty = [%d]" % (mll_hook.m_struct.pt.x,mll_hook.m_struct.pt.y) return CallNextHookEx( mll_hook.hook, nCode, wParam, lParam ) if __name__ == '__main__': print "Press the middle mouse button to exit " try: mll_hook.hook = SetWindowsHookEx(win32con.WH_MOUSE_LL, LowLevelMouseProc, GetModuleHandle(0), 0) except Exception, err: print err # set up a message queue, you can use any valid message loop tkinter, pygtk and wxpythons message loops all work win32gui.PumpMessages() # unhook the mouse hook UnhookWindowsHookEx(mll_hook.hook) ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:PycURL模塊的使用,這個模塊功能和urllib同樣,是C語言寫的,速度很是快 參數數量:太多 參數列表: 返回數量: 返回值列表: 使用方法: ''' #!/usr/bin/env python # -*- coding: utf-8 -*- import StringIO import pycurl def getHtml(myurl): html = StringIO.StringIO() c = pycurl.Curl() ## myurl='http://www.lpfrx.com' c.setopt(pycurl.URL, myurl) #寫的回調 c.setopt(pycurl.WRITEFUNCTION, html.write) c.setopt(pycurl.FOLLOWLOCATION, 1) #最大重定向次數,能夠預防重定向陷阱 c.setopt(pycurl.MAXREDIRS, 5) #鏈接超時設置 c.setopt(pycurl.CONNECTTIMEOUT, 60) c.setopt(pycurl.TIMEOUT, 300) #模擬瀏覽器 c.setopt(pycurl.USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)") #訪問,阻塞到訪問結束 c.perform() #打印出 200(HTTP狀態碼) print c.getinfo(pycurl.HTTP_CODE) #輸出網頁的內容 ##print html.getvalue() #輸出網頁類型 print "Content-type:", c.getinfo(c.CONTENT_TYPE) return html.getvalue() ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:給你一個域名列表,你能夠得到他的ip,以及地理位置 參數數量:1 參數列表: 返回數量: 返回值列表: 使用方法: if "__main__" == __name__: fw = open('shsihsi.txt','w') fw.write(str(getIPByDomain('adhotspot.biz')[0]) + '\n') bb = getAddrByIP('78.46.253.75') if bb.find('德國')+1: print 'aaaa' fw.write( bb+ '\n') fw.close() ''' #!/usr/bin/env python # -*- coding: utf-8 -*- import re import time import urllib2 import cookielib def getIPByDomain(domain): data = '' relist = [] urlPathOne = "http://www.ip138.com/ips1388.asp?ip=" + domain + "&action=2" cj = cookielib.CookieJar() auth_handler = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(urllib2.HTTPSHandler(),auth_handler,urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) URL_Start = urlPathOne try: handle = urllib2.urlopen(URL_Start) handle.close() except IOError, e: print e relist.append('error') return relist time.sleep(0.5) try: a = urllib2.urlopen(URL_Start) html = a.read() a.close() if html.find('<h1>') +1: temp = html[html.find('<h1>') : html.find('</h1>')] ## iptem = temp[ : temp.find('<tr class="grey-bg bottom-border" >')] sdata = temp p = r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' mo = re.compile(p) m = mo.search(sdata) if not m: relist.append('NULL') return relist else: iplist = mo.findall(sdata) return iplist else: relist.append('NULL') return relist except: return ['error'] def getAddrByIP(ip): data = '' addr = '' urlPathOne = "http://www.ip.cn/index.php?ip="+ip req_header = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0',\ 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\ 'Accept-Language':'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',\ 'Cookie':'anonymid=hwyz9f6r-ipg7xm; jebe_key=f7c92a91-c7e9-4b69-bdc1-bf5f766b8132%7Ca22b0134bed0e5baa9f32a412aad1b46%7C1403968344919%7C1%7C1403968331677; depovince=JL; _r01_=1; jebecookies=39fccb4d-c041-4891-af90-ab5c553d21c7|||||; ick_login=5449ca00-3317-47c1-b668-c56cca3ab128; _de=37E78EAE52CFD393416FD9B685238F34F4489C1C70DDCBF9; p=ba366aeeaba84cca4169e2c0d286811a1; ap=341251011; first_login_flag=1; t=6f2c8f21365082101c61dbf5f01bb20f1; societyguester=6f2c8f21365082101c61dbf5f01bb20f1; id=341251011; xnsid=1cf75790; loginfrom=null',\ 'Accept-Encoding':'deflate', ##這個地方要注意 不能使壓縮的 \ 'Connection':'keep-alive',\ 'Referer':'http://page.renren.com' ##注意若是依然不能抓取的話,這裏能夠設置抓取網站的host\ } req_timeout = 3 try: req = urllib2.Request(urlPathOne,None,req_header) resp = urllib2.urlopen(req,None,req_timeout) data = resp.read() resp.close() raws = data.split('\n') dedao = '' for raw in raws: if raw.find(r'查詢的 IP:')+1: dedao = raw break ## print dedao addr = dedao.replace(r'<div id="result"><div class="well">',' ').replace(r' ','') addr = addr.replace(r'<p>',' ').replace(r'</p>',' ') addr = addr.replace(r'<code>',' ').replace(r'</code>',' ') addr = addr.replace(r'<div>',' ').replace(r'</div>',' ') addr = addr[addr.find(r'來自:')+6:].replace(r':','') except: print 'error' return addr ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:給你一個域名列表,你能夠得到他的ip,以及地理位置 參數數量:域名orip 參數列表: 返回數量:2 返回值列表: 返回ip和地址 使用方法: ''' #!/usr/bin/env python # -*- coding: utf-8 -*- import re import time import urllib2 import cookielib def getIPandAddrByDomain(ip): time.sleep(0.1) data = '' addr = '' iip = '' urlPathOne = "http://www.ip.cn/index.php?ip="+ip req_header = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0',\ 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\ 'Accept-Language':'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',\ 'Cookie':'anonymid=hwyz9f6r-ipg7xm; jebe_key=f7c92a91-c7e9-4b69-bdc1-bf5f766b8132%7Ca22b0134bed0e5baa9f32a412aad1b46%7C1403968344919%7C1%7C1403968331677; depovince=JL; _r01_=1; jebecookies=39fccb4d-c041-4891-af90-ab5c553d21c7|||||; ick_login=5449ca00-3317-47c1-b668-c56cca3ab128; _de=37E78EAE52CFD393416FD9B685238F34F4489C1C70DDCBF9; p=ba366aeeaba84cca4169e2c0d286811a1; ap=341251011; first_login_flag=1; t=6f2c8f21365082101c61dbf5f01bb20f1; societyguester=6f2c8f21365082101c61dbf5f01bb20f1; id=341251011; xnsid=1cf75790; loginfrom=null',\ 'Accept-Encoding':'deflate', ##這個地方要注意 不能使壓縮的 \ 'Connection':'keep-alive',\ 'Referer':'http://page.renren.com' ##注意若是依然不能抓取的話,這裏能夠設置抓取網站的host\ } req_timeout = 3 try: req = urllib2.Request(urlPathOne,None,req_header) resp = urllib2.urlopen(req,None,req_timeout) data = resp.read() resp.close() raws = data.split('\n') dedao = '' for raw in raws: if raw.find(r'查詢的 IP:')+1: dedao = raw break ## print dedao addr = dedao.replace(r'<div id="result"><div class="well">',' ').replace(r' ','') addr = addr.replace(r'<p>',' ').replace(r'</p>',' ') iip = addr[: addr.find('</code>')] iip = iip.strip().replace('查詢的 IP:<code>','') addr = addr.replace(r'<code>',' ').replace(r'</code>',' ') addr = addr.replace(r'<div>',' ').replace(r'</div>',' ') addr = addr[addr.find(r'來自:')+6:].replace(r':','') except: print str(ip) + ' error' return iip,addr ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:讓另外一個窗口抖動 參數數量: 參數列表: 返回數量: 返回值列表: 使用方法: ''' # -*- coding: cp936 -*- import random import win32gui import win32api,win32con import ctypes #定義結構體,存儲當前窗口座標 class RECT(ctypes.Structure): _fields_ = [('left', ctypes.c_int), ('top', ctypes.c_int), ('right', ctypes.c_int), ('bottom', ctypes.c_int)] rect = RECT() ##HWND = 0x0002015E ##spy++直接得到句柄 ##HWND = win32gui.FindWindow(0, u'下載') HWND = win32gui.GetForegroundWindow()#獲取當前窗口句柄 if HWND == 0: print 'error' print HWND else: ctypes.windll.user32.GetWindowRect(HWND, ctypes.byref(rect))#獲取當前窗口座標 step = 2 for i in range(2,200): win32gui.SetWindowPos(HWND, None, rect.left+step*random.randint(1,i%6+2), rect.top-step*random.randint(1,i%6+2), rect.right-rect.left, rect.bottom-rect.top, win32con.SWP_NOSENDCHANGING|win32con.SWP_SHOWWINDOW)#實現更改當前窗口位置 win32gui.SetWindowPos(HWND, None, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, win32con.SWP_NOSENDCHANGING|win32con.SWP_SHOWWINDOW)#將窗口恢復至初始位置 ##==================================================================== ##--------------------------------------------------------------------- ''' 功能:NTFS備用數據流,能隱藏文件 參數數量: 參數列表: 返回數量: 返回值列表: ''' fr = open('cmd.exe','rb') data = fr.read() fr.close() fw = open('cmd.exe:cmdliu2.exe','wb') fw.write(data) fw.close() ##==================================================================== ##--------------------------------------------------------------------- ''' 注意: 功能:對字符串進行url過濾,提取url 參數數量:1 參數列表: 待提取字串 返回數量:1 返回值列表: 一個url列表 使用方法: ''' import re sdata ='www.baidu.cn\n\ http://218.76.201.87/file/MDAwMDAwMDHEp9A5DFfuXUbmT5AwgkswSnKWacB4rSbdYM1Sd4tR3g../e274bd63acfe3479ef1720967821086e2c739c/VA_X_dll.rar?key=AAABQFQAKrP7x5NA&p=&a=2625127-13e635d-48049-0/010100&mode=download \ http://blog.sina.com.cn/s/blog_a15aa56901017liq.html \ baidu.com/img/baidu_aa.gif \ http://www.baidu.com/s?wd=python%20url%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F&ie=utf-8&tn=baiduhome_pg&oq=url%20zhengze&f=8&rsv_bp=1&rsv_spt=1&rsv_sug3=7&rsv_sug4=1315&rsv_sug1=1&rsv_sug2=0&inputT=1331&rsv_sug=1&bs=url%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F \ http://baidu.com/aa.gif \ baidu.com.cn.org/bb/cc.asp \ www.baidu.org/dd/ee/ff.php?n=44&m=yy sdfsdfsdf' def findAllUrl(p_strings): iplist = [] relist = [] # http:// baidu . com /aa/bb . php ? a = cc & ee = ss p = r'(([\w]+\://)*[\w]+(?:\.[\w]+)+(?:/[\w\_]+)*((\.)[\w]+)*((\?[\w\%\-\_]+=[\w\%\-\_/]*)*(&[\w\%\-\_]+=[\w\%\-\_/]*)*))' mo = re.compile(p) m = mo.search(p_strings) if not m: iplist.append('NULL') else: iplist = mo.findall(p_strings) for il in iplist: relist.append(il[0]) return relist ##====================================================================