Package: mitmdump
mitmdumpmitmdump是对mitmproxy的简单封装，实现以编程的方式运行 mitmproxy
服务, 方便我们开箱即用，而不再需要记住复杂的命令参数，当然原来的命令行方式运行也是支持的，另外对于某些特殊的应用场景，我们还可以借助 Pycharm
对编写的 mitmproxy 脚本进行断点调试。安装pip install mitmdump运行Before:mitmdump -s youscript.pyAfter:python youscript.pyormitmdump -s youscript.py示例# sample1.pyfrommitmproxy.httpimportHTTPFlowfrommitmdumpimportDumpMaster,OptionsclassAddHeader:def__init__(self):self.num=0defresponse(self,flow:HTTPFlow):self.num=self.num+1flow.response.headers["count"]=str(self.num)addons=[AddHeader()]if__name__=='__main__':opts=Options(listen_host='0.0.0.0',listen_port=8888,scripts=__file__)m=DumpMaster(opts)m.run()# sample2.pyfrommitmproxyimportflowfilter,ctx,addonmanagerfrommitmproxy.httpimportHTTPFlowfrommitmdumpimportDumpMaster,OptionsclassFilterFlow:def__init__(self):self.filter=Nonedefload(self,loader:addonmanager.Loader):self.filter=flowfilter.parse(ctx.options.dumper_filter)defrequest(self,flow:HTTPFlow):ifflowfilter.match(self.filter,flow):print(flow.request.url)defresponse(self,flow:HTTPFlow):ifflowfilter.match(self.filter,flow):print(flow.response.headers)addons=[FilterFlow()]if__name__=='__main__':opts=Options(listen_host='0.0.0.0',listen_port=8888,scripts=None,dumper_filter='~m POST',flow_detail=1,termlog_verbosity='info',show_clientconnect_log=False)m=DumpMaster(opts)# It's necessary if scripts parameter is None# 如果你的 scripts 参数为 None，则下方加载插件的语句是必须要有的m.addons.add(*addons)m.run()更多官网示例参数列表mitmdump 库所有可用的参数都保持跟 mitmproxy
一致，所以你不必担心使用上的困难，以下列举了可用参数及类型，参数具体说明可参考对应命令行中的帮助信息。paramsdefaulttypeadd_upstream_certs_to_client_chainFalse[<class 'bool'>]allow_hosts[][typing.Sequence[str]]anticacheFalse[<class 'bool'>]anticompFalse[<class 'bool'>]block_globalTrue[<class 'bool'>]block_privateFalse[<class 'bool'>]body_size_limitNone[typing.Union[str, NoneType]]certs[][typing.Sequence[str]]ciphers_clientNone[typing.Union[str, NoneType]]ciphers_serverNone[typing.Union[str, NoneType]]client_certsNone[typing.Union[str, NoneType]]client_replay[][typing.Sequence[str]]command_historyTrue[<class 'bool'>]confdir~/.mitmproxy[<class 'str'>]content_view_lines_cutoff512[<class 'int'>]dumper_default_contentviewauto[<class 'str'>]dumper_filterNone[typing.Union[str, NoneType]]flow_detail1[<class 'int'>]http2True[<class 'bool'>]http2_priorityFalse[<class 'bool'>]ignore_hosts[][typing.Sequence[str]]keep_host_headerFalse[<class 'bool'>]keepservingFalse[<class 'bool'>]key_size2048[<class 'int'>]listen_host0.0.0.0[<class 'str'>]listen_port8080[<class 'int'>]map_local[][typing.Sequence[str]]map_remote[][typing.Sequence[str]]moderegular[<class 'str'>]modify_body[][typing.Sequence[str]]modify_headers[][typing.Sequence[str]]onboardingTrue[<class 'bool'>]onboarding_hostmitm.it[<class 'str'>]onboarding_port80[<class 'int'>]proxyauthNone[typing.Union[str, NoneType]]rawtcpFalse[<class 'bool'>]readfile_filterNone[typing.Union[str, NoneType]]rfileNone[typing.Union[str, NoneType]]save_stream_fileNone[typing.Union[str, NoneType]]save_stream_filterNone[typing.Union[str, NoneType]]scripts[][typing.Sequence[str]]serverTrue[<class 'bool'>]server_replay[][typing.Sequence[str]]server_replay_ignore_contentFalse[<class 'bool'>]server_replay_ignore_hostFalse[<class 'bool'>]server_replay_ignore_params[][typing.Sequence[str]]server_replay_ignore_payload_params[][typing.Sequence[str]]server_replay_ignore_portFalse[<class 'bool'>]server_replay_kill_extraFalse[<class 'bool'>]server_replay_nopopFalse[<class 'bool'>]server_replay_refreshTrue[<class 'bool'>]server_replay_use_headers[][typing.Sequence[str]]showhostFalse[<class 'bool'>]show_clientconnect_logFalse[<class 'bool'>]spoof_source_addressFalse[<class 'bool'>]ssl_insecureFalse[<class 'bool'>]ssl_verify_upstream_trusted_caNone[typing.Union[str, NoneType]]ssl_verify_upstream_trusted_confdirNone[typing.Union[str, NoneType]]ssl_version_clientsecure[<class 'str'>]ssl_version_serversecure[<class 'str'>]stickyauthNone[typing.Union[str, NoneType]]stickycookieNone[typing.Union[str, NoneType]]stream_large_bodiesNone[typing.Union[str, NoneType]]stream_websocketsFalse[<class 'bool'>]tcp_hosts[][typing.Sequence[str]]termlog_verbosityinfo[<class 'str'>]upstream_authNone[typing.Union[str, NoneType]]upstream_bind_address[<class 'str'>]upstream_certTrue[<class 'bool'>]websocketTrue[<class 'bool'>]命令行帮助信息usage:mitmdump[options][filter]positionalarguments:filter_argsFilterexpression,equivalenttosettingboththeview_filterandsave_stream_filteroptions.

optionalarguments:-h,--helpshowthishelpmessageandexit--versionshowversionnumberandexit--optionsShowalloptionsandtheirdefaultvalues--commandsShowallcommandsandtheirsignatures--setoption[=value]Setanoption.Whenthevalueisomitted,booleansaresettotrue,stringsandintegersaresettoNone(ifpermitted),andsequencesareemptied.Booleanvaluescanbetrue,falseortoggle.-q,--quietQuiet.-v,--verboseIncreaselogverbosity.--modeMODE,-mMODEModecanbe"regular","transparent","socks5","reverse:SPEC",or"upstream:SPEC".Forreverseandupstreamproxymodes,SPECishostspecificationintheformof"http[s]://host[:port]".--no-anticache--anticacheStripoutrequestheadersthatmightcausetheservertoreturn304-not-modified.--no-showhost--showhostUsetheHostheadertoconstructURLsfordisplay.--rfilePATH,-rPATHReadflowsfromfile.--scriptsSCRIPT,-sSCRIPTExecuteascript.Maybepassedmultipletimes.--stickycookieFILTERSetstickycookiefilter.Matchedagainstrequests.--stickyauthFILTERSetstickyauthfilter.Matchedagainstrequests.--save-stream-filePATH,-wPATHStreamflowstofileastheyarrive.Prefixpathwith+toappend.--no-anticomp--anticompTrytoconvinceserverstosendusun-compresseddata.--flow-detailLEVELThedisplaydetaillevelforflowsinmitmdump:0(almostquiet)to3(veryverbose).0:shortenedrequestURL,responsestatuscode,WebSocketandTCPmessagenotifications.1:fullrequestURLwithresponsestatuscode2:1+HTTPheaders3:2+fullresponsecontent,contentofWebSocketandTCPmessages.

ProxyOptions:--listen-hostHOSTAddresstobindproxyto.--listen-portPORT,-pPORTProxyserviceport.--no-server,-n--serverStartaproxyserver.Enabledbydefault.--ignore-hostsHOSTIgnorehostandforwardalltrafficwithoutprocessingit.Intransparentmode,itisrecommendedtouseanIPaddress(range),notthehostname.Inregularmode,onlySSLtrafficisignoredandthehostnameshouldbeused.Thesuppliedvalueisinterpretedasaregularexpressionandmatchedontheiporthehostname.Maybepassedmultipletimes.--allow-hostsHOSTOppositeof--ignore-hosts.Maybepassedmultipletimes.--tcp-hostsHOSTGenericTCPSSLproxymodeforallhoststhatmatchthepattern.Similarto--ignore,butSSLconnectionsareintercepted.Thecommunicationcontentsareprintedtotheloginverbosemode.Maybepassedmultipletimes.--upstream-authUSER:PASSAddHTTPBasicauthenticationtoupstreamproxyandreverseproxyrequests.Format:username:password.--proxyauthSPECRequireproxyauthentication.Format:"username:pass","any"toacceptanyuser/passcombination,"@path"touseanApachehtpasswdfile,or"ldap[s]:url_server_ldap:dn_auth:password:dn_subtree"forLDAPauthentication.--no-rawtcp--rawtcpEnable/disableexperimentalrawTCPsupport.TCPconnectionsstartingwithnon-asciibytesaretreatedasiftheywouldmatchtcp_hosts.Theheuristicisveryrough,usewithcaution.Disabledbydefault.--no-http2--http2Enable/disableHTTP/2support.HTTP/2supportisenabledbydefault.

SSL:--certsSPECSSLcertificatesoftheform"[domain=]path".Thedomainmayincludeawildcard,andisequalto"*"ifnotspecified.ThefileatpathisacertificateinPEMformat.IfaprivatekeyisincludedinthePEM,itisused,elsethedefaultkeyintheconfdirisused.ThePEMfileshouldcontainthefullcertificatechain,withtheleafcertificateasthefirstentry.Maybepassedmultipletimes.--no-ssl-insecure--ssl-insecure,-kDonotverifyupstreamserverSSL/TLScertificates.--key-sizeKEY_SIZETLSkeysizeforcertificatesandCA.

ClientReplay:--client-replayPATH,-CPATHReplayclientrequestsfromasavedfile.Maybepassedmultipletimes.

ServerReplay:--server-replayPATH,-SPATHReplayserverresponsesfromasavedfile.Maybepassedmultipletimes.--no-server-replay-kill-extra--server-replay-kill-extraKillextrarequestsduringreplay.--no-server-replay-nopop--server-replay-nopopDon'tremoveflowsfromserverreplaystateafteruse.Thismakesitpossibletoreplaysameresponsemultipletimes.--no-server-replay-refresh--server-replay-refreshRefreshserverreplayresponsesbyadjustingdate,expiresandlast-modifiedheaders,aswellasadjustingcookieexpiration.

MapRemote:--map-remotePATTERN,-MPATTERNMapremoteresourcestoanotherremoteURLusingapatternoftheform"[/flow-filter]/url-regex/replacement",wheretheseparatorcanbeanycharacter.Maybepassedmultipletimes.

MapLocal:--map-localPATTERNMapremoteresourcestoalocalfileusingapatternoftheform"[/flow-filter]/url-regex/file-or-directory-path",wheretheseparatorcanbeanycharacter.Maybepassedmultipletimes.

ModifyBody:--modify-bodyPATTERN,-BPATTERNReplacementpatternoftheform"[/flow-filter]/regex/[@]replacement",wheretheseparatorcanbeanycharacter.The@allowstoprovideafilepaththatisusedtoreadthereplacementstring.Maybepassedmultipletimes.

ModifyHeaders:--modify-headersPATTERN,-HPATTERNHeadermodifypatternoftheform"[/flow-filter]/header-name/[@]header-value",wheretheseparatorcanbeanycharacter.The@allowstoprovideafilepaththatisusedtoreadtheheadervaluestring.Anemptyheader-valueremovesexistingheader-nameheaders.Maybepassedmultipletimes.