python迴圈監控遠程連接埠的方法

來源:互聯網
上載者:User
本文執行個體講述了python迴圈監控遠程連接埠的方法。分享給大家供大家參考。具體如下:

在ip.txt中每行一個ip地址和連接埠號碼,代碼可迴圈監控這些ip地址的指定連接埠是否正常

#!/usr/bin/env python# -*- coding: gbk -*-import socket,timewhile 1:  file_obj = open('ip.txt')  for line in file_obj:    try:      sc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)      ip = line.split()[0]      port = int(line.split()[1])      print ip,port      #設定逾時時間(0.0)      sc.settimeout(2)      sc.connect((ip,port))      timenow=time.localtime()      datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)      logstr="%s:%s 串連成功->%s \n" %(ip,port,datenow)      print logstr      sc.close()    except:      file = open("log.txt", "a")      timenow=time.localtime()      datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)      logstr="%s:%s 串連失敗->%s \n" %(ip,port,datenow)      print logstr      file.write(logstr)      file.close()  print "sleep 10....."  time.sleep(10)

ip.txt格式檔案:

192.168.1.100 33001192.168.1.101 33001

希望本文所述對大家的Python程式設計有所協助。

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.