2016-01-13 75 views
0

我知道如何基本打印使用鬆弛API發送通知鬆懈,例如,如果我有一個鬆弛通道名爲#testbot,所以我可以打印通知爲:如何打印通知鬆懈通過調用python函數

slack.chat.post_message('#testbot','This is a test',username='NMAP_bot') 

我下面在我有2類Python和以上所有的限定一個作爲方法的面向對象之路探尋:

def notify_slack(): 

class Report(object): 
    . 
    . 
    def new_hosts(self): 
     """Return a list of new hosts added in latest scan""" 
     self.curr_hosts - self.prev_hosts 

    . 
    . 

class Scanner(object): 
    . 
    #Lot of code here 

我有基本上看起來像一個主要方法:

if __name__ == "__main__":    
     print "New Hosts" 
     report.new_hosts()  #This calls new_hosts() method in class Report 

所以,report.new_hosts()能夠調用報告類中定義的方法,並打印出結果。 我想要做的就是調用notify_slack()並通過report.new_hosts()裏面,所以它打印結果懈怠。

任何幫助表示讚賞,指導我!

+0

*返回新主機*名單 - 該方法只是打印,沒有回報...... –

+0

哦,是的..因此,如果該方法返回,那麼我怎麼進行呢? – PythonFreak

+0

你調用該方法,並將結果傳遞給其他方法 –

回答

0

你需要改變new_hosts方法,而不是返回打印出來的它的結果:

class Report(object): 
    . 
    . 
    def new_hosts(self): 
     """Return a list of new hosts added in latest scan""" 
     return self.curr_hosts - self.prev_hosts 

你需要改變的notify_slack這樣定義的,它需要一個參數,它會是調用report.new_host的結果:

def notify_slack(host_list): 
    # Don't notify Slack if list of hosts is empty 
    if not host_list: 
     return 

    slack_msg = ' '.join(map(str, msg_list)) 
    slack.chat.post_message('#testbot', slack_msg,username='NMAP_bot') 

report.new_hosts()調用的結果然後可以送入噸他notify_slack方法。

notify_slack(report.new_hosts()) 
+0

如果我想也把狀態發送給內部notify_slack(msg_list)懈怠之前,該msg_list不爲空,即如果new_hosts()返回一個空列表,然後沒有通知鬆弛,否則是 – PythonFreak

+0

您可以檢查'msg_list'的長度,如果長度爲0或更小,則返回。我將編輯'notify_slack'方法。 – gnerkus

0

我想要做的就是調用notify_slack(),並通過report.new_hosts()裏面

喜歡這個?

def notify_slack(hosts): 
    print hosts 
    msg = ' '.join(map(str, hosts)) # delimits all the hosts by space 
    slack.chat.post_message('#testbot',msg,username='NMAP_bot') 


class Report(object): 
    def new_hosts(self): 
     """Return a list of new hosts added in latest scan""" 
     return self.curr_hosts - self.prev_hosts 

# s = ? 
r = s.run("172.16.0.0-255") 
report = Report(r) 
notify_slack(report.new_hosts()) 
+0

感謝的人,工作正常 – PythonFreak