首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

fiddler2调试工具脚本-当地假数据及远程调用

2014-01-03 
fiddler2调试工具脚本--本地假数据及远程调用接受某著名博主的建议, 在写技术文档的时候加入个人特色, 嘿

fiddler2调试工具脚本--本地假数据及远程调用

接受某著名博主的建议, 在写技术文档的时候加入个人特色, 嘿嘿, 支持原创, 保护劳动成果, 欢迎转载.

?

这里的脚本是针对著名web调试代理工具fiddler2所写的, 那Aaron君在工作中总是遇到后台不能同步完成工作的情况, 需要搞一些假数据来做UT, 另外还有需要调用不同站点接口数据测试的需求. Aaron君比较懒,不想总是改动代码, 因此写了一个小工具也就是一个脚本加上一个配置文件来完成这2项工作.?

?

?

CustumRules.js代码如下?

83 public static RulesOption("&Disable Caching", "Per&formance") 84 var m_DisableCaching: boolean = false; 85 86 // Show the duration between the start of Request.Send and Response.Completed in Milliseconds 87 public static RulesOption("&Show Time-to-Last-Byte", "Per&formance") 88 var m_ShowTTLB: boolean = false; 89 90 // Show the time of response completion 91 public static RulesOption("Show Response &Timestamp", "Per&formance") 92 var m_ShowTimestamp: boolean = false; 93 94 public static RulesOption("Cache Always &Fresh", "Per&formance") 95 var m_AlwaysFresh: boolean = false; 96 97 // Force a manual reload of the script file. Resets all 98 // RulesOption variables to their defaults. 99 public static ToolsAction("Reset Script")100 function DoManualReload() { 101 FiddlerObject.ReloadScript();102 }103 104 public static ContextAction("Decode Selected Sessions")105 function DoRemoveEncoding(oSessions: Session[]) {106 for (var x:int = 0; x < oSessions.Length; x++){107 oSessions[x].utilDecodeRequest();108 oSessions[x].utilDecodeResponse();109 }110 FiddlerApplication.UI.actUpdateInspector(true,true);111 }112 113 static function OnBoot() {114 // MessageBox.Show("Fiddler has finished booting");115 // System.Diagnostics.Process.Start("iexplore.exe");116 117 // FiddlerObject.UI.ActivateRequestInspector("HEADERS");118 // FiddlerObject.UI.ActivateResponseInspector("HEADERS");119 }120 121 static function OnShutdown() {122 // MessageBox.Show("Fiddler has shutdown");123 }124 125 static function OnAttach() {126 // MessageBox.Show("Fiddler is now the system proxy");127 // System.Diagnostics.Process.Start("proxycfg.exe", "-u"); // Notify WinHTTP of proxy change128 }129 130 static function OnDetach() {131 // MessageBox.Show("Fiddler is no longer the system proxy");132 // System.Diagnostics.Process.Start("proxycfg.exe", "-u"); // Notify WinHTTP of proxy change133 }134 135 /** public static **/136 public static var CFG_PATH: String = "D:\\cfg.ini";137 public static var cfg: Object = getCfg(CFG_PATH);138 139 140 public static var localRgx = RegExp(cfg.local.split(",").join('|'));141 public static var remoteRgx = RegExp(cfg.remote.split(",").join('|'));142 143 // left trim144 static function LTrim(str) {145 for (var i=0; str.charAt(i)==" "; i++);146 return str.substring(i,str.length);147 }148 // right trim149 static function RTrim(str) {150 for (var i=str.length-1; str.charAt(i)==" "; i--);151 return str.substring(0,i+1);152 }153 // trim154 static function Trim(str) {155 return LTrim(RTrim(str));156 }157 // is Empty158 static function isEmpty(D){159 return D===null||D===undefined||(true?D==="":false);160 }161 // return an array of lines in the file162 static function readFile(path, type) {163 var fs = new ActiveXObject("Scripting.FileSystemObject");164 165 if(!fs.FileExists(path))166 return "file not found!";167 168 var f = fs.GetFile(path);169 170 // Open the file 171 var is = f.OpenAsTextStream(1, 0 );172 var count = 0, rline = new Array();173 174 if(type == "array") {175 while( !is.AtEndOfStream ){176 rline[count] = is.ReadLine();177 count++;178 }179 is.Close();180 } else if(type == "string") {181 rline = "";182 while( !is.AtEndOfStream ){183 rline += is.ReadLine();184 rline += "\n";185 count++;186 }187 is.Close();188 }189 fs = null;190 return rline;191 }192 193 // create 194 static function createFile(path, get2Str, post2Str) {195 var fs = new ActiveXObject("Scripting.FileSystemObject");196 if(!fs.FileExists(path)) {197 var f = fs.CreateTextFile(path);198 199 var strs2write = [];200 strs2write.push('/******************************************/', '\n', '/** file name', '\n');201 // print file name202 strs2write.push(path.split("\").pop(), '\n\n', '/** params', '\n');203 //print params204 var params = get2Str.split('&').concat(post2Str.split('&'));205 206 for(var i = 0; i < params.length; i++) {207 strs2write.push(params[i], '\n');208 }209 210 strs2write.push('\n', '/******************************************/');211 f.Write(strs2write.join(''));212 f.Close();213 }214 fs = null;215 216 }217 218 219 // get config obj 220 static function getCfg(path) {221 var rl = readFile(path, "array");222 var c = {};223 224 for(var i = 0; i < rl.length; i++){225 if(rl[i].charAt(0) == ";") continue;226 227 var index = rl[i].indexOf(":");228 229 if(index != -1) {230 var pName = rl[i].substring(0, index);231 var pValue = rl[i].substring(index + 1);232 233 c[Trim(String(pName))] = Trim(String(pValue));234 }235 236 }237 238 return c;239 }240 241 // reload cfg242 static function reloadCfg() {243 cfg = getCfg(CFG_PATH);244 localRgx = RegExp(cfg.local.split(",").join('|'));245 remoteRgx = RegExp(cfg.remote.split(",").join('|'));246 }247 /** public static end **/248 static function OnBeforeRequest(oSession: Session) {249 // Sample Rule: Color ASPX requests in RED250 // if (oSession.uriContains(".aspx")) { oSession["ui-color"] = "red"; }251 252 // Sample Rule: Flag POSTs to fiddler2.com in italics253 // if (oSession.HostnameIs("www.fiddler2.com") && oSession.HTTPMethodIs("POST")) { oSession["ui-italic"] = "yup"; }254 255 // Sample Rule: Break requests for URLs containing "/sandbox/"256 // if (oSession.uriContains("/sandbox/")) {257 // oSession.oFlags["x-breakrequest"] = "yup"; // Existence of the x-breakrequest flag creates a breakpoint; the "yup" value is unimportant.258 // }259 260 /** sef-defined options **/261 262 // FiddlerObject.alert(cfg['local'])263 264 reloadCfg();265 266 if (localRgx.test(oSession.url)) {267 // FiddlerObject.alert(oSession)268 269 /* var aa = oSession.url.split("/");270 var ajax = aa[aa.length - 1].split('?')[0];271 var host = aa[0];272 var getParams = oSession.PathAndQuery.split('?')[1];273 var redirector = 'localhost/redirect.php'274 275 oSession.url = redirector + '?ajax=' + ajax + (!!getParams ? '&' + getParams : ''); */276 277 } else if (remoteRgx.test(oSession.url)) {//FiddlerObject.alert(remoteRgx)278 if (oSession.HTTPMethodIs("CONNECT")/* && (oSession.PathAndQuery == "10.160.74.59:443") */) { 279 oSession.PathAndQuery = cfg.remoteAddress; 280 }281 282 if (true/* oSession.HostnameIs("10.160.74.59") */) {283 oSession.hostname = cfg['remoteAddress'];284 oSession.oRequest["Cookie"] = cfg["remoteCookie"];285 }286 }287 /** sef-defined options end **/288 289 if ((null != gs_ReplaceToken) && (oSession.url.indexOf(gs_ReplaceToken)>-1)) { // Case sensitive290 oSession.url = oSession.url.Replace(gs_ReplaceToken, gs_ReplaceTokenWith); 291 }292 if ((null != gs_OverridenHost) && (oSession.host.toLowerCase() == gs_OverridenHost)) {293 oSession["x-overridehost"] = gs_OverrideHostWith; 294 }295 296 if ((null!=bpRequestURI) && oSession.uriContains(bpRequestURI)) {297 oSession["x-breakrequest"]="uri";298 }299 300 if ((null!=bpMethod) && (oSession.HTTPMethodIs(bpMethod))) {301 oSession["x-breakrequest"]="method";302 }303 304 if ((null!=uiBoldURI) && oSession.uriContains(uiBoldURI)) {305 oSession["ui-bold"]="QuickExec";306 }307 308 if (m_SimulateModem) {309 // Delay sends by 300ms per KB uploaded.310 oSession["request-trickle-delay"] = "300"; 311 // Delay receives by 150ms per KB downloaded.312 oSession["response-trickle-delay"] = "150"; 313 }314 315 if (m_DisableCaching) {316 oSession.oRequest.headers.Remove("If-None-Match");317 oSession.oRequest.headers.Remove("If-Modified-Since");318 oSession.oRequest["Pragma"] = "no-cache";319 }320 321 // User-Agent Overrides322 if (null != sUA) {323 oSession.oRequest["User-Agent"] = sUA; 324 }325 326 if (m_Japanese) {327 oSession.oRequest["Accept-Language"] = "ja";328 }329 330 if (m_AutoAuth) {331 // Automatically respond to any authentication challenges using the 332 // current Fiddler user's credentials. You can change (default)333 // to a domain\\username:password string if preferred.334 //335 // WARNING: This setting poses a security risk if remote 336 // connections are permitted!337 oSession["X-AutoAuth"] = "(default)";338 }339 340 if (m_AlwaysFresh && (oSession.oRequest.headers.Exists("If-Modified-Since") || oSession.oRequest.headers.Exists("If-None-Match")))341 {342 oSession.utilCreateResponseAndBypassServer();343 oSession.responseCode = 304;344 oSession["ui-backcolor"] = "Lavender";345 }346 347 348 }349 350 /* // SAMPLES 351 352 // You can create a custom menu like so:353 QuickLinkMenu("&Links") 354 QuickLinkItem("IE GeoLoc TestDrive", "http://ie.microsoft.com/testdrive/HTML5/Geolocation/Default.html")355 QuickLinkItem("FiddlerCore", "http://fiddler.wikidot.com/fiddlercore")356 public static function DoLinksMenu(sText: String, sAction: String)357 {358 Utilities.LaunchHyperlink(sAction);359 }360 361 // This function is called immediately after a set of request headers has362 // been read from the client. This is typically too early to do much useful363 // work, since the body hasn't yet been read, but sometimes it may be useful.364 //365 // For instance, see 366 // http://blogs.msdn.com/b/fiddler/archive/2011/11/05/http-expect-continue-delays-transmitting-post-bodies-by-up-to-350-milliseconds.aspx367 // for one useful thing you can do with this handler.368 //369 // Note: oSession.requestBodyBytes is not available within this function!370 static function OnPeekAtRequestHeaders(oSession: Session) {371 }372 */373 374 //375 // If a given session has response streaming enabled, then the OnBeforeResponse function 376 // is actually called AFTER the response was returned to the client.377 //378 // In contrast, this OnPeekAtResponseHeaders function is called before the response headers are 379 // sent to the client (and before the body is read from the server). Hence this is an opportune time 380 // to disable streaming (oSession.bBufferResponse = true) if there is something in the response headers 381 // which suggests that tampering with the response body is necessary.382 // 383 // Note: oSession.responseBodyBytes is not available within this function!384 //385 static function OnPeekAtResponseHeaders(oSession: Session) {386 //FiddlerApplication.Log.LogFormat("Session {0}: Response header peek shows status is {1}", oSession.id, oSession.responseCode);387 if (m_DisableCaching) {388 oSession.oResponse.headers.Remove("Expires");389 oSession.oResponse["Cache-Control"] = "no-cache";390 }391 392 if ((bpStatus>0) && (oSession.responseCode == bpStatus)) {393 oSession["x-breakresponse"]="status";394 oSession.bBufferResponse = true;395 }396 397 if ((null!=bpResponseURI) && oSession.uriContains(bpResponseURI)) {398 oSession["x-breakresponse"]="uri";399 oSession.bBufferResponse = true;400 }401 402 }403 404 static function OnBeforeResponse(oSession: Session) {405 if (m_ShowTimestamp){406 oSession["ui-customcolumn"] = DateTime.Now.ToString("H:mm:ss.ffff") + " " + oSession["ui-customcolumn"]; 407 }408 409 if (m_ShowTTLB){410 oSession["ui-customcolumn"] = oSession.oResponse.iTTLB + "ms " + oSession["ui-customcolumn"]; 411 }412 413 if (m_Hide304s && oSession.responseCode == 304){414 oSession["ui-hide"] = "true";415 }416 417 /** self defined begin**/418 reloadCfg();419 420 if (localRgx.test(oSession.url)) {421 var url = oSession.PathAndQuery.split("?")[0].split("/").pop(),422 get2Str = oSession.PathAndQuery.split("?")[1]||"",423 post2Str = oSession.GetRequestBodyAsString();424 425 var fName = url + (isEmpty(get2Str)?"":("&"+get2Str)) + (isEmpty(post2Str)?"":("&"+post2Str));426 427 // avoid long file name428 if(fName.length > 200)429 fName = fName.substring(0, 200);430 // remove time signature431 fName = fName.replace(/\&\_dc\=[^\&]*/g, "");432 433 fName = fName + ".json";434 435 var path = cfg["dataPath"] + fName;436 //FiddlerObject.alert(path)437 if(cfg.autoGen == "1") createFile(path, get2Str, post2Str);438 439 if(readFile(path, "string") == "file not found!") return;440 441 oSession.utilSetResponseBody(readFile(path, "string"));442 } else if (remoteRgx.test(oSession.url)) {}443 /** self defined end**/444 }445 446 /*447 // This function executes just before Fiddler returns an error that it has 448 // itself generated (e.g. "DNS Lookup failure") to the client application.449 // These responses will not run through the OnBeforeResponse function above.450 static function OnReturningError(oSession: Session) {451 }452 */453 454 static function Main() {455 var today: Date = new Date();456 FiddlerObject.StatusText = " CustomRules.js was loaded at: " + today;457 // Uncomment to add a "Server" column containing the response "Server" header, if present458 // FiddlerObject.UI.lvSessions.AddBoundColumn("Server", 50, "@response.server");459 }460 461 // These static variables are used for simple breakpointing & other QuickExec rules 462 static var bpRequestURI:String = null;463 static var bpResponseURI:String = null;464 static var bpStatus:int = -1;465 static var bpMethod: String = null;466 static var uiBoldURI: String = null;467 static var gs_ReplaceToken: String = null;468 static var gs_ReplaceTokenWith: String = null;469 static var gs_OverridenHost: String = null;470 static var gs_OverrideHostWith: String = null;471 472 // The OnExecAction function is called by either the QuickExec box in the Fiddler window,473 // or by the ExecAction.exe command line utility.474 static function OnExecAction(sParams: String[]) {475 476 FiddlerObject.StatusText = "ExecAction: " + sParams[0];477 478 var sAction = sParams[0].toLowerCase();479 switch (sAction) {480 case "bold":481 if (sParams.Length<2) {uiBoldURI=null; FiddlerObject.StatusText="Bolding cleared"; return;}482 uiBoldURI = sParams[1]; FiddlerObject.StatusText="Bolding requests for " + uiBoldURI;483 break;484 case "bp":485 FiddlerObject.alert("bpu = breakpoint request for uri\nbpm = breakpoint request method\nbps=breakpoint response status\nbpafter = breakpoint response for URI");486 break;487 case "bps":488 if (sParams.Length<2) {bpStatus=-1; FiddlerObject.StatusText="Response Status breakpoint cleared"; return;}489 bpStatus = parseInt(sParams[1]); FiddlerObject.StatusText="Response status breakpoint for " + sParams[1];490 break;491 case "bpv":492 case "bpm":493 if (sParams.Length<2) {bpMethod=null; FiddlerObject.StatusText="Request Method breakpoint cleared"; return;}494 bpMethod = sParams[1].toUpperCase(); FiddlerObject.StatusText="Request Method breakpoint for " + bpMethod;495 break;496 case "bpu":497 if (sParams.Length<2) {bpRequestURI=null; FiddlerObject.StatusText="RequestURI breakpoint cleared"; return;}498 bpRequestURI = sParams[1]; 499 FiddlerObject.StatusText="RequestURI breakpoint for "+sParams[1];500 break;501 case "bpafter":502 if (sParams.Length<2) {bpResponseURI=null; FiddlerObject.StatusText="ResponseURI breakpoint cleared"; return;}503 bpResponseURI = sParams[1]; 504 FiddlerObject.StatusText="ResponseURI breakpoint for "+sParams[1];505 break;506 case "overridehost":507 if (sParams.Length<3) {gs_OverridenHost=null; FiddlerObject.StatusText="Host Override cleared"; return;}508 gs_OverridenHost = sParams[1].toLowerCase();509 gs_OverrideHostWith = sParams[2];510 FiddlerObject.StatusText="Connecting to [" + gs_OverrideHostWith + "] for requests to [" + gs_OverridenHost + "]";511 break;512 case "urlreplace":513 if (sParams.Length<3) {gs_ReplaceToken=null; FiddlerObject.StatusText="URL Replacement cleared"; return;}514 gs_ReplaceToken = sParams[1];515 gs_ReplaceTokenWith = sParams[2].Replace(" ", "%20"); // Simple helper516 FiddlerObject.StatusText="Replacing [" + gs_ReplaceToken + "] in URIs with [" + gs_ReplaceTokenWith + "]";517 break;518 case "allbut":519 case "keeponly":520 if (sParams.Length<2) { FiddlerObject.StatusText="Please specify Content-Type to retain during wipe."; return;}521 FiddlerObject.UI.actSelectSessionsWithResponseHeaderValue("Content-Type", sParams[1]);522 FiddlerObject.UI.actRemoveUnselectedSessions();523 FiddlerObject.UI.lvSessions.SelectedItems.Clear();524 FiddlerObject.StatusText="Removed all but Content-Type: " + sParams[1];525 break;526 case "stop":527 FiddlerObject.UI.actDetachProxy();528 break;529 case "start":530 FiddlerObject.UI.actAttachProxy();531 break;532 case "cls":533 case "clear":534 FiddlerObject.UI.actRemoveAllSessions();535 break;536 case "g":537 case "go":538 FiddlerObject.UI.actResumeAllSessions();539 break;540 case "goto":541 if (sParams.Length != 2) return;542 Utilities.LaunchHyperlink("http://www.google.com/search?hl=en&btnI=I%27m+Feeling+Lucky&q=" + Utilities.UrlEncode(sParams[1]));543 break;544 case "help":545 Utilities.LaunchHyperlink("http://www.fiddler2.com/redir/?id=quickexec");546 break;547 case "hide":548 FiddlerObject.UI.actMinimizeToTray();549 break;550 case "log":551 FiddlerApplication.Log.LogString((sParams.Length<2) ? FiddlerApplication.Log.LogString("User couldn't think of anything to say...") : sParams[1]);552 break;553 case "nuke":554 FiddlerObject.UI.actClearWinINETCache();555 FiddlerObject.UI.actClearWinINETCookies(); 556 break;557 case "show":558 FiddlerObject.UI.actRestoreWindow();559 break;560 case "tail":561 if (sParams.Length<2) { FiddlerObject.StatusText="Please specify # of sessions to trim the session list to."; return;}562 FiddlerObject.UI.TrimSessionList(int.Parse(sParams[1]));563 break;564 case "quit":565 FiddlerObject.UI.actExit();566 break;567 case "dump":568 FiddlerObject.UI.actSelectAll();569 FiddlerObject.UI.actSaveSessionsToZip(CONFIG.GetPath("Captures") + "dump.saz");570 FiddlerObject.UI.actRemoveAllSessions();571 FiddlerObject.StatusText = "Dumped all sessions to " + CONFIG.GetPath("Captures") + "dump.saz";572 break;573 574 default:575 if (sAction.StartsWith("http") || sAction.StartsWith("www")){576 System.Diagnostics.Process.Start(sParams[0]);577 }578 else579 {580 FiddlerObject.StatusText = "Requested ExecAction: '" + sAction + "' not found. Type HELP to learn more.";581 }582 }583 }584 }

配置文件如下

;;;;;;;;;;;;;;本地数据配置;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;调用本地文件的ajax集合(如果重复配置了ajax,优先调用本地文件)local:aaa_ajax;假数据存放路径dataPath : D:\\UED\\data\\2344\\; 自动生成本地假数据文件开关 0 关闭 1 打开autoGen : 0;;;;;;;;;;;;;;远程数据配置;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;调用远程接口的ajax集合remote : webp_ajax;远程数据地址remoteAddress : 10.160.71.12;远程设备的cookie(需要登录盒子后在浏览器控制台中手动拷贝过来)remoteCookie : username=hillstone; passwd=fooground; UILanguage=2; cookieUserName=fooground; cookieUserPriv=4294967295; vsysName=root; _WebSessionId_=afcbc40ae910016ff9151f59febaff37; LoginId=pUqZpLVyUm5Wv/1qFLoz; LoginTime=1370601425; vsysid=0

大家可以先用这2个文件试一试, 具体用法稍后解释~  

热点排行