Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python批量扫描服务器端口

$
0
0

闲来无事用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."

这个脚本有一个不足的地方,虽然可以批量扫描服务器,但是不能批量扫描端口。当然,想要增加这个功能也很容易,或者哪位大神有更好的脚本也可以贴出来学习学习。


Viewing all articles
Browse latest Browse all 9596

Trending Articles