我們在使用一些開源程序之前,可能會使用ab工具在服務器或者本地進行一次性能評估,但是很多時候卻總是會以失敗告終,因為,服務器會拒絕你的ab工具發出的http請求, 出現 error: connection reset by peer, 這該怎么辦呢?
首先,為了測試一個具有sql操作的頁面,通常需要登錄,這時候需要偽裝成一個用戶來實現自動登錄,簡單的方法就是:在瀏覽器端登錄一個用戶,打開chrome的developer tool,將其中的cookie復制,用-H option來實現帶cookie的http請求,其余的並發任務交給ab工具,使得每個http都攜帶session對應的cookie,如果這樣就ok了,基本上說明這個web app安全性有待考量,這也是初級使用者可能忽略的問題。
其次,如果偽裝成登錄用戶,攜帶了cookie依然出現這個錯誤,那么通常是由於web app源碼中開啟了csrf防護,針對偽裝的請求做了過濾,這個問題也相對好解決,因為是開放源碼,我們可以打開源碼,找到這個web app的框架級的config文件,或者是 application級別的啟動器類,就可以方便快速地找到這段程序,將csrf防護關閉就可以了。以下就以rails應用, 和 sails.js應用為例,講述如何關閉csrf防護。
rails應用:代碼在controller目錄下的ApplicationController.rb文件,將其中的csrf保護函數protect_from_forgery中cookie.delete(auto_cookie_name)行注釋掉。或者將protect_from_forgery注釋掉,代碼如下:
class ApplicationController < ActionController::Base include Redmine::I18n include Redmine::Pagination include RoutesHelper helper :routes class_attribute :accept_api_auth_actions class_attribute :accept_rss_auth_actions class_attribute :model_object layout 'base' protect_from_forgery def handle_unverified_request super #cookies.delete(autologin_cookie_name) end before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token rescue_from ::Unauthorized, :with => :deny_access rescue_from ::ActionView::MissingTemplate, :with => :missing_template include Redmine::Search::Controller include Redmine::MenuManager::MenuController helper Redmine::MenuManager::MenuHelper def session_expiration if session[:user_id] if session_expired? && !try_to_autologin reset_session flash[:error] = l(:error_session_expired) redirect_to signin_url else #session[:atime] = Time.now.utc.to_i end end end
如果是sails.js web app, 那么就更加簡單了,打開config目錄下,有一個csrf文件,將csrf設置為false就可以了。
在關閉了csrf之后,基本上ab測試就不會再出現error: connection reset by peer 了。
如果你對手頭沒有源碼的web app的性能測試感興趣,可以參考我的其它文章。
參考:
檢查丟包利器dropwatch: http://blog.yufeng.info/archives/2497
ulimit問題及其影響: http://blog.yufeng.info/archives/1380