Python批量掃描伺服器連接埠,python掃描伺服器端
閑來無事用Python寫了一個簡陋的連接埠掃描指令碼,其簡單的邏輯如下:
1. python DetectHostPort.py iplist.txt(存放著需要掃描的IP地址清單的文本,每行一個地址)
2. 輸入掃描連接埠、掃描時間和掃描間隔。
3. 輸出掃描資訊。
下面貼上源碼,歡迎拍磚。
1 #!/usr/bin/env python 2 3 import sys 4 import time 5 import socket 6 7 8 def getaddresslist(addr): 9 """10 getaddresslist(addr) -> IP address file11 12 IP address read from the file.13 :param addr: IP file14 :return: Scan ip address list, or error message.15 """16 address = []17 try:18 with open(addr, "r") as iplist:19 line = iplist.readlines()20 for item in line:21 address.append(item.strip("\n"))22 return address23 24 except (IOError, IndexError), e:25 return str(e)26 27 28 def scan(iplist, port=80):29 """30 scan() -> getaddresslist()31 32 getaddresslist() function returns the IP address of the list.33 :param iplist: getaddresslist() Function return value.34 :param port: Need to scan the port.35 :return: None36 """37 if not isinstance(iplist, list):38 sys.exit("Function getaddresslist() return error message: %s" % iplist)39 # start_time = time.time()40 41 for addr in iplist:42 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)43 s.settimeout(1)44 host = (addr, int(port))45 46 try:47 s.connect(host)48 print "Host %s:%s connection success." % (host[0], host[1])49 except Exception, e:50 print "Host %s:%s connection failure: %s" % (host[0], host[1], e)51 52 s.close()53 54 # print "Port scanning to complate, Elapsed time: %.2f" % (time.time() - start_time)55 56 if __name__ == '__main__':57 58 addrs = sys.argv[1]59 # ScanPort = raw_input("Enter the scan port <default is 80 port>: ")60 61 ScanPort = input("Enter the scan port: ")62 Total = input("Enter the scan time <minutes>: ")63 Interval = input("Enter the scanning interval <minutes>: ")64 65 EndTime = time.time() + Total * 6066 67 while time.time() < EndTime:68 scan(getaddresslist(addrs), ScanPort)69 time.sleep(Interval * 60)70 continue71 else:72 print "\nwhile end."
這個指令碼有一個不足的地方,雖然可以批量掃描伺服器,但是不能批量掃描連接埠。當然,想要增加這個功能也很容易,或者哪位大神有更好的指令碼也可以貼出來學習學習。