閑來無事用Python寫了一個簡陋的埠掃描腳本,其簡單的邏輯如下: 1. python DetectHostPort.py iplist.txt(存放著需要掃描的IP地址列表的文本,每行一個地址) 2. 輸入掃描埠、掃描時間和掃描間隔。 3. 輸出掃描信息。 下麵貼上源碼,歡迎拍磚。 這個腳本有 ...
閑來無事用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(addrs): 9 """ 10 getaddresslist(addr) -> IP address file 11 12 IP address read from the file. 13 :param addrs: IP file 14 :return: Scan ip address list, or error message. 15 """ 16 address = [] 17 try: 18 with open(addrs, "r") as iplist: 19 line = iplist.readlines() 20 for item in line: 21 address.append(item.strip("\n")) 22 return address 23 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: None 36 """ 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 * 60 66 67 while time.time() < EndTime: 68 scan(getaddresslist(addrs), ScanPort) 69 time.sleep(Interval * 60) 70 continue 71 else: 72 print "\nwhile end."
這個腳本有一個不足的地方,雖然可以批量掃描伺服器,但是不能批量掃描埠。當然,想要增加這個功能也很容易,或者哪位大神有更好的腳本也可以貼出來學習學習。