2016-07-04 107 views
2

如何從Python中ping服務器?Python:如何ping服務器?

我想獲得一個ping腳本工作。我使用pxssh登錄到服務器,並且一旦登錄,ping一個IP地址。我需要檢查是否有任何損失等..以下是我的腳本,但看到一些錯誤...可以幫助任何人。我正在使用sendline將命令發送到服務器。

def pingGW(self): 
       s.sendline('ping 127.0.0.1 -c 5 > /etc/dhcp/ping.txt') 
       s.prompt() 
       s.sendline('cd /etc/dhcp/') 
       s.prompt() 

       str = '100% packet loss' 
       jes = open((s.sendline('vi /etc/dhcp/ping.txt')), 'r') 
       for line in jes: 
         if re.search(str, line): 
           print 'Cannot reach the gateway' 

       print "Ping success" 

:錯誤消息:

JES =開放((s.sendline( '六/etc/dhcp/ping.txt')),「R

s= pxssh.pxssh() 
class DhcpServer: 

     def connect(self,**kwargs): 
       self.dhcp_server = kwargs.get('dhcp_server',None) 
       self.username = kwargs.get('user_name', None) 
       self.password = kwargs.get('password',None) 
       s.login(self.dhcp_server,self.username,self.password) 
       print "Connected to server" 

def pingGW(self): 
       s.sendline('ping 127.0.0.1 -c 5 > /etc/dhcp/ping.txt') 
       s.prompt() 
       s.sendline('cd/etc/dhcp/') 
       s.prompt() 

       str = '100% packet loss' 
       jes = open((s.sendline('vi /etc/dhcp/ping.txt')), 'r') 
       for line in jes: 
         if re.search(str, line): 
           print 'Cannot reach the gateway' 
正確indendation後

「)類型錯誤:強迫爲Unicode:需要字符串或緩衝區,詮釋發現[jesgeorg @ INS-qasvr-18 LIB] $

+2

你可以張貼的錯誤? – enthus1ast

+1

'def pingGW'沒有正確縮進。 – enthus1ast

+1

我對pxssh不熟悉,但是''pingGW()'方法沒有正確縮進,'sendline('cd')'命令需要cd和path之間的空格。 –

回答

0

如果你是用Python中執行ping只是感興趣:

import ping 
ping.verbose_ping("example.com") 

https://pypi.python.org/pypi/ping/0.2

關於你原來的問題,sendline()不會做你的想法。它寫入「僞終端」會話,就像有人正在打字一樣。你不需要這樣做來打開文件。

如果你要打開的文件,只需

fd = open('/etc/dhcp/ping.txt') 
+0

我需要使用sendline()向服務器發送命令。 ping.txt文件存儲在服務器的/ etc/dhcp flder內部。如果我做一個正常的fd = open(// etc/dhcp ..')它不會從服務器打開文件..它會看本地機器..這不是我想要的 –