用python做自動化測試--Python實現遠程性能監控


http://blog.csdn.net/powerccna/article/details/8044222

在性能測試中,監控被測試服務器的性能指標是個重要的工作,包括CPU/Memory/IO/Network,但大多數人估計都是直接在被測試服務器的運行監控程序。我們開始也是這樣做的。但這樣做帶來一個問題是,測試人員需要在每台被測試服務器上部署監控程序,增加了部署的工作量,而且經常因為Python版本的問題,有些模塊不兼容,或者第三方模塊需要再次安裝。

       改進性能測試監控工具:

1. 能遠程監控被測試服務器,這樣測試人員就不需要在每個被測試機器安裝監控工具了。

         2. 被測試服務器上不需要安裝agent,監控結果能取到本地。

        3. 本地服務器上的python模塊和兼容性問題,可以通過Python  virtualenv解決,每個測試人員維護自己的一套Python環境。

 

Google了下,找到了pymeter(thttp://pymeter.sourceforge.net/), 看了下源代碼,很多工作還沒完成,但這個思路和我的是一樣的。而且我在其他項目中已經實現了遠程發送命令的模塊。 所以不如直接在自己的項目上擴展。

 

遠程發送命令的模塊開始是基於Pexpect(http://www.noah.org/wiki/Pexpect)實現的, Pexpect很強大,它是一個用來啟動子程序,並使用正則表達式對程序輸出做出特定響應,以此實現與其自動交互的 Python 模塊。用他來可以很容易實現telnet,ftp,ssh的操作。 但Pexpect無windows下的版本,這是我拋棄它的原因,無法達到測試工具兼容所有系統的要求。 所以就用telent模塊替換了Pexpect,實現了遠程發送命令和獲取結果。

#file name: telnetoperate.py

 
  1. #!/usr/bin/env python  
  2. #coding=utf-8  
  3.   
  4. import time,sys,logging,traceback,telnetlib,socket  
  5.   
  6.   
  7. class TelnetAction:  
  8.     def __init__(self,host,prompt,account,accountPasswd,RootPasswd=""):  
  9.         self.log=logging.getLogger()  
  10.         self.host=host  
  11.         self.account=account  
  12.         self.accountPasswd=accountPasswd  
  13.         self.RootPasswd=RootPasswd  
  14.         self.possible_prompt = ["#","$"]  
  15.         self.prompt=prompt  
  16.         self.default_time_out=20  
  17.         self.child =None  
  18.         self.login()  
  19.       
  20.     def expand_expect(self,expect_list):  
  21.         try:  
  22.             result=self.child.expect(expect_list,self.default_time_out)  
  23.         except EOFError:  
  24.             self.log.error("No text was read, please check reason")  
  25.         if result[0]==-1:  
  26.             self.log.error("Expect result"+str(expect_list)+" don't exist")  
  27.         else:  
  28.             pass  
  29.         return result  
  30.   
  31.     def login(self):  
  32.         """Connect to a remote host and login. 
  33.              
  34.         """  
  35.         try:  
  36.             self.child = telnetlib.Telnet(self.host)  
  37.             self.expand_expect(['login:'])  
  38.             self.child.write(self.account+ '\n')  
  39.             self.expand_expect(['assword:'])  
  40.             self.child.write(self.accountPasswd + '\n')  
  41.             self.expand_expect(self.possible_prompt)  
  42.             self.log.debug("swith to root account on host "+self.host)  
  43.             if self.RootPasswd!="":  
  44.                 self.child.write('su -'+'\n')  
  45.                 self.expand_expect(['assword:'])  
  46.                 self.child.write(self.RootPasswd+'\n')  
  47.                 self.expand_expect(self.possible_prompt)  
  48.             #self.child.write('bash'+'\n')  
  49.             #self.expand_expect(self.possible_prompt)  
  50.             self.child.read_until(self.prompt)  
  51.             self.log.info("login host "+self.host+" successfully")  
  52.             return True  
  53.         except:  
  54.             print "Login failed,please check ip address and account/passwd"  
  55.             self.log.error("log in host "+self.host+" failed, please check reason")  
  56.             return False  
  57.   
  58.     def send_command(self,command,sleeptime=0.5):  
  59.         """Run a command on the remote host. 
  60.              
  61.         @param command: Unix command 
  62.         @return: Command output 
  63.         @rtype: String 
  64.         """  
  65.         self.log.debug("Starting to execute command: "+command)  
  66.         try:  
  67.             self.child.write(command + '\n')  
  68.             if self.expand_expect(self.possible_prompt)[0]==-1:  
  69.                 self.log.error("Executed command "+command+" is failed, please check it")  
  70.                 return False  
  71.             else:  
  72.                 time.sleep(sleeptime)  
  73.                 self.log.debug("Executed command "+command+" is successful")  
  74.                 return True  
  75.         except socket.error:  
  76.             self.log.error("when executed command "+command+" the connection maybe break, reconnect")  
  77.             traceback.print_exc()  
  78.             for i in range(0,3):  
  79.                 self.log.error("Telnet session is broken from "+self.host+ ", reconnecting....")  
  80.                 if self.login():  
  81.                     break  
  82.             return False  
  83.   
  84.     def get_output(self,time_out=2):  
  85.         reponse=self.child.read_until(self.prompt,time_out)  
  86.         #print "response:",reponse  
  87.         self.log.debug("reponse:"+reponse)  
  88.         return  self.__strip_output(reponse)  
  89.           
  90.     def send_atomic_command(self, command):  
  91.         self.send_command(command)  
  92.         command_output = self.get_output()  
  93.         self.logout()  
  94.         return command_output  
  95.       
  96.     def process_is_running(self,process_name,output_string):      
  97.         self.send_command("ps -ef | grep "+process_name+" | grep -v grep")  
  98.         output_list=[output_string]  
  99.         if self.expand_expect(output_list)[0]==-1:  
  100.             return False  
  101.         else:  
  102.             return True  
  103.       
  104.     def __strip_output(self, response):  
  105.         #Strip everything from the response except the actual command output.  
  106.           
  107.         #split the response into a list of the lines  
  108.           
  109.         lines = response.splitlines()  
  110.         self.log.debug("lines:"+str(lines))  
  111.         if len(lines)>1:  
  112.             #if our command was echoed back, remove it from the output  
  113.             if self.prompt in lines[0]:  
  114.                 lines.pop(0)  
  115.             #remove the last element, which is the prompt being displayed again  
  116.             lines.pop()  
  117.             #append a newline to each line of output  
  118.             lines = [item + '\n' for item in lines]  
  119.             #join the list back into a string and return it  
  120.             return ''.join(lines)  
  121.         else:  
  122.             self.log.info("The response is blank:"+response)  
  123.             return "Null response"  
  124.       
  125.     def logout(self):  
  126.           
  127.         self.child.close()  

telnetoperate.py代碼說明:

1.  __init__(self,host,prompt,account,accountPasswd,RootPasswd="")

  這里用到了多個登陸賬號(account,root),原因是我們的機器開始不能直接root登陸,需要先用普通用戶登陸,才能切換到root賬號,所以這里出現了account, rootPasswd這2個參數,如果你的機器可以直接root賬號登陸,或者你不需要切換到root賬號,可以就用account, accountPasswd就可以了。

  prompt是命令行提示符,機器配置不一樣,可能是$或者#,用來判斷一個命令執行是否完成。

 

2.  send_command(self,command,sleeptime=0.5)

    這里sleeptime=0.5是為了避免很多機器性能不好,命令執行比較慢,命令還沒返回,會導致獲取命令后的結果失敗。如果你嫌這樣太慢了,可以調用的時候send_command(command,0)

process_is_running(

process_name 

 

監控遠程機器:

#simplemonitor.py

  1. #!/usr/bin/env python  
  2. #coding=utf-8  
  3.   
  4. import time  
  5. import telnetoperate  
  6.   
  7.   
  8.   
  9. remote_server=telnetoperate.TelnetAction("192.168.23.235","#","user","passwd123")  
  10. #get cpu information  
  11. cpu=remote_server.get_output("sar 1 1 |tail -1")  
  12. memory=remote_server.get_output("top | head -5 |grep -i memory")  
  13. io=remote_server.get_output("iostat -x 1 2|grep -v '^$' |grep -vi 'dev'")  
  14.       

 

 

這樣在任何一台機器上就可以實現監控遠程多個機器了,信息集中化管理,方便進一步分析。如果你想cpu, memory, io獨立的監控,可以多線程或者起多個監控進程,在多線程中需要注意的時候,必須對每個監控實例建立一個telnet連接,get_output是從telnet 建立的socket里面去獲取數據,如果多個監控實例用同一個socket會導致數據混亂。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM