这其实是我自己写的一些简单的功能方法,当然有很大一部分代码是借鉴别人的代码,新手,写这个博客只为python学习阶段的积累
#!/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'
##1、将空格编码为%20
encodeUrl = urllib.quote(decodedUrl)
print encodeUrl
##2、将空格编码为+加号 这个比较常用
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
##====================================================================