端口檢查指令
lsof
lsof -i:端口號
用于查詢某一端口的占用情況,比如查詢我們熟悉的3306端口的使用情況,可以使用lsof -i:3306
root@iZbp11s2rh7xf6u48hlcroZ:~# lsof -i:3306
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
mysqld 20109 mysql 16u IPv6 50086 0t0 TCP *:mysql (LISTEN)
可以看到3306端口已經被mysql數據庫的守護進程mysqld
給占用了。
netstat
netstat -tunpl|grep 端口號
,用于查看指定的端口號的進程情況,如查看3306端口的進程情況,可以使用netstat -tunpl|grep 3306
root@iZbp11s2rh7xf6u48hlcroZ:~# netstat -tunpl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:32000 0.0.0.0:* LISTEN 4350/java
tcp 0 0 127.0.0.1:8005 0.0.0.0:* LISTEN 16977/java
tcp 0 0 0.0.0.0:8009 0.0.0.0:* LISTEN 16977/java
tcp 0 0 0.0.0.0:6379 0.0.0.0:* LISTEN 23371/redis-server
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 16977/java
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 911/sshd
tcp 0 0 127.0.0.1:8088 0.0.0.0:* LISTEN 18522/influxd
tcp6 0 0 :::3306 :::* LISTEN 20109/mysqld
tcp6 0 0 :::6379 :::* LISTEN 23371/redis-server
tcp6 0 0 :::8086 :::* LISTEN 18522/influxd
udp 0 0 0.0.0.0:68 0.0.0.0:* 614/dhclient
udp 0 0 172.16.113.172:123 0.0.0.0:* 755/ntpd
udp 0 0 127.0.0.1:123 0.0.0.0:* 755/ntpd
udp 0 0 0.0.0.0:123 0.0.0.0:* 755/ntpd
udp6 0 0 :::123 :::* 755/ntpd
root@iZbp11s2rh7xf6u48hlcroZ:~# netstat -tunpl|grep 3306
tcp6 0 0 :::3306 :::* LISTEN 20109/mysqld
對上述指令中的關鍵參數進行一下介紹:
-t (tcp):僅顯示tcp相關的選項;
-u(udp):僅顯示udp相關的選項;
-n:拒絕顯示別名,能顯示為數字的全部顯示為數字;
-p:顯示建立連接的程序名;
-l:僅列出在listen的服務狀態;
端口掃描程序
下面給出一個python編寫的簡單的掃描的端口占用檢測的程序ip_scan.py
,該程序可以檢測指定的IP地址下0-65534端口的占用情況,完整的腳本程序如下,無需引用任何的第三方的包:
#!/usr/bin/env python
# -*- encoding:utf-8 -*-
import socket, time, thread
socket.setdefaulttimeout(3) # 設置套接字的默認超時時間
def socket_scan(ip, port):
"""
輸入IP和端口號,掃描判斷端口是否被占用
:param ip: 待掃描的IP地址
:param port: 待掃描的端口號
:return:
"""
try:
if port > 65535:
print u'端口掃描結束'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 使用了socket.connect_ex方法,該方法不會拋出異常,只會給出錯誤碼,
result = s.connect_ex((ip, port))
# 如果錯誤碼為0表示成功連上了某個端口;如果返回其他值表示出錯了,端口沒有打開。
if result == 0:
lock.acquire()
print ip, u':', port, u'端口已經被占用'
lock.release()
except:
print u'端口掃描異常'
def ip_scan(ip):
"""
輸入IP地址,掃描0-65534端口情況
:param ip:
:return:
"""
try:
print u'開始掃描 %s' % ip
start_time = time.time()
for i in range(0, 65534):
thread.start_new_thread(socket_scan, (ip, int(i)))
print u'端口掃描完成,總共耗時:%.2f秒' % (time.time() - start_time)
# raw_input("Please press enter to exit")
except:
print u'掃描ip出錯'
if __name__ == '__main__':
ip_address = raw_input("Please input the IP address you want to scan: ")
lock = thread.allocate_lock()
ip_scan(ip_address)
在本人的一臺阿里云的云主機上的測試結果如下所示:
root@iZbp11s2rh7xf6u48hlcroZ:/home/louxj424/document# python ip_scan.py
Please input the IP address you want to scan: 127.0.0.1
開始掃描 127.0.0.1
127.0.0.1 : 22 端口已經被占用
127.0.0.1 : 3306 端口已經被占用
127.0.0.1 : 6379 端口已經被占用
127.0.0.1 : 8005 端口已經被占用
127.0.0.1 : 8009 端口已經被占用
127.0.0.1 : 8080 端口已經被占用
127.0.0.1 : 8086 端口已經被占用
127.0.0.1 : 8088 端口已經被占用
127.0.0.1 : 32000 端口已經被占用
端口掃描完成,總共耗時:5.05秒