之前项目上线前,领导要求让写一个脚本用来判断端口的占用情况。由于现在python3使用也比较多,基于python2修改了一下,做了个python3版本的,现在做一下总结。
一、python脚本实现扫描端口:
pthon2下代码如下(当时的环境):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
import socket, time, thread
socket.setdefaulttimeout( 3 )
def socket_port(ip, port):
try :
if port > = 65535 :
print u '端口扫描结束'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((ip, port))
if result = = 0 :
lock.acquire()
print ip,u ':' ,port,u '端口已占用'
lock.release()
except :
print u '端口扫描异常'
def ip_scan(ip):
try :
print u '开始扫描 %s' % ip
start_time = time.time()
for i in range ( 0 , 65534 ):
thread.start_new_thread(socket_port,(ip, int (i)))
print u '扫描端口完成,总共用时:%.2f' % (time.time() - start_time)
except :
print u '扫描ip出错'
if __name__ = = '__main__' :
url = raw_input ( 'Input the ip you want to scan: ' )
lock = thread.allocate_lock()
ip_scan(url)
|
效果图:

python3的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
import socket,time,_thread
socket.setdefaulttimeout( 3 )
def socket_port(ip, port):
try :
if port > = 65535 :
print (u '端口扫描结束' )
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((ip, port))
if result = = 0 :
lock.acquire()
print (ip,u ':' ,port,u '端口已占用' )
lock.release()
except :
print (u '端口扫描异常' )
def ip_scan(ip):
try :
print (u '开始扫描 %s' % ip)
start_time = time.time()
for i in range ( 0 , 65534 ):
_thread.start_new_thread(socket_port,(ip, int (i)))
print (u '扫描端口完成,总共用时:%.2f' % (time.time() - start_time))
except :
print (u '扫描ip出错' )
if __name__ = = '__main__' :
url = input ( 'Input the ip you want to scan: ' )
lock = _thread.allocate_lock()
ip_scan(url)
|
效果:
二、linux命令判断
1. lsof -i:端口号 用于查看指定端口号的占用情况,如下查看80端口的情况。
2.netstat -tunlp |grep 端口号,用于查看指定的端口号的进程情况,如查看25端口的情况,netstat -tunlp |grep 25
三、写python脚本中出现的问题
1.ImportError: No module named 'thread'
说没有thread这个模块,python3中没有了thread模块,取而代之的是_thread和threading(推荐使用),_thread是为了过渡使用的。
2.IndentationError: unindent does not match any outer indentation level
百度后发现原因是因为混用了空格和tab。
tab键设置为4位。vim /etc/vimrc 增加set ts=4
本文转自 ping9527 51CTO博客,原文链接:http://blog.51cto.com/babyhanggege/1940700,如需转载请自行联系原作者