欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實現(xiàn)Windows端口監(jiān)聽程序

 更新時間:2025年05月09日 09:12:52   作者:CATTLECODE  
這篇文章主要為大家詳細(xì)介紹了如何使用Python實現(xiàn)Windows端口監(jiān)聽程序,從而打印出對本機處于監(jiān)聽狀態(tài)的端口,進(jìn)程ID和程序名稱,感興趣的可以了解下

1、安裝庫

pip install tabulate

2、代碼實現(xiàn)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
"""
Windows端口監(jiān)聽程序
顯示本機處于監(jiān)聽狀態(tài)的端口,進(jìn)程ID和程序名稱
"""
 
import subprocess
import re
import os
import sys
from tabulate import tabulate
 
def get_listening_ports():
    """
    獲取所有處于監(jiān)聽狀態(tài)的端口信息
    返回包含端口、PID和程序名稱的列表
    """
    try:
        # 使用netstat命令獲取所有TCP監(jiān)聽端口
        netstat_output = subprocess.check_output(
            'netstat -ano -p tcp | findstr "LISTENING"',
            shell=True, 
            text=True
        )
        
        # 解析netstat輸出
        port_info = []
        for line in netstat_output.splitlines():
            # 清理并分割行
            parts = re.split(r'\s+', line.strip())
            if len(parts) >= 5:
                # 提取本地地址和PID
                local_address = parts[1]
                pid = parts[4]
                
                # 從本地地址中提取端口
                if ':' in local_address:
                    port = local_address.split(':')[-1]
                    
                    # 獲取進(jìn)程名稱
                    try:
                        process_info = subprocess.check_output(
                            f'tasklist /fi "PID eq {pid}" /fo csv /nh',
                            shell=True,
                            text=True
                        )
                        
                        # 解析進(jìn)程信息
                        if process_info and '","' in process_info:
                            process_name = process_info.split('","')[0].strip('"')
                            port_info.append({
                                'port': port,
                                'pid': pid,
                                'program': process_name
                            })
                    except subprocess.SubprocessError:
                        port_info.append({
                            'port': port,
                            'pid': pid,
                            'program': 'Unknown'
                        })
        
        return port_info
    
    except subprocess.SubprocessError as e:
        print(f"獲取端口信息時出錯: {e}")
        return []
 
def display_port_info(port_info):
    """
    以表格形式顯示端口信息
    """
    if not port_info:
        print("未找到監(jiān)聽中的端口")
        return
    
    # 準(zhǔn)備表格數(shù)據(jù)
    table_data = []
    for info in port_info:
        table_data.append([
            info['port'],
            info['pid'],
            info['program']
        ])
    
    # 按端口號排序
    table_data.sort(key=lambda x: int(x[0]) if x[0].isdigit() else float('inf'))
    
    # 顯示表格
    headers = ["端口", "進(jìn)程ID", "程序名稱"]
    print(tabulate(table_data, headers=headers, tablefmt="grid"))
 
def main():
    """
    主函數(shù)
    """
    print("正在獲取本機監(jiān)聽端口信息...\n")
    port_info = get_listening_ports()
    display_port_info(port_info)
 
if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n程序被用戶中斷")
    except Exception as e:
        print(f"程序執(zhí)行出錯: {e}")
        sys.exit(1)

3、效果如下

4、知識延展

python監(jiān)聽端口并重啟服務(wù)腳本

通過python運行系統(tǒng)命令,netstat -aon|findstr 端口號,查看端口是否占用,如果占用著,說明服務(wù)沒掛,不做處理,sleep設(shè)置的時間,然后再重新運行查看端口占用命令;如果沒占用,說明服務(wù)掛了,重新運行啟動腳本,xxxx.bat,啟動服務(wù)。

依賴包:

  • os(windows命令)
  • time(定時)

代碼:

######################
# 根據(jù)端口自動重啟腳本~ #
######################
import os
import time

port = input("\n>>>請輸入端口: \n")
# C:/Users/syp1293/Desktop/configfile/center.bat
bat_path = input("\n>>>請輸入bat文件路徑: \n")
time_u = input("\n>>>請輸入間隔時間: \n")
while True:
    with os.popen('netstat -aon|findstr "' + port + '"') as res:
        res = res.read().split('\n')
    result = []
    if res[0] == '':
        # 不存在端口占用,啟動服務(wù)
        os.system('start ' + bat_path)
        time.sleep(120)
        continue
    else:
        for line in res:
            # print(line)
            temp = [i for i in line.split(' ') if i != '']
            if len(temp) > 4:
                #  result.append({'pid': temp[4], 'address': temp[1], 'state': temp[3]})
                print('PID:', temp[4])
    # print('sleeping...')
    time.sleep(int(time_u))

生成exe文件,并且啟動后顯示為命令行。

pyinstaller -F osport.py

Python socket端口監(jiān)聽

實現(xiàn)代碼

import struct
import socket
import time
import multiprocessing as mp
SERVER_IP = "192.168.1.33"
PORT_BASE = 30000
import os
def recvall(conn, n):
    # Helper function to recv n bytes or return None if EOF is hit
    data = b''
 
    while len(data) < n:
        packet = conn.recv(n - len(data))
        if not packet:
            #print("hahahah","come here")
            break
        data += packet
        #print(len(data))
    #print("result ======",len(data))
    return data
 
def recv_data(conn):
    # result = result.decode("utf8")
    data = b''
    counts = 0
    while True:
        packet = conn.recv(1024)
        counts += len(packet)
        if not packet:
            break
        data += packet
    print("++++++++++++++++",len(data),counts)
    return data
 
def listen_client(port):
    #server_port = PORT_BASE + port
    # try its best to listen to bind the ports to receive data
    while True:
        try:
            recv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            recv_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            recv_socket.bind((SERVER_IP,port))
            print(" listening ",SERVER_IP,port)
            recv_socket.listen()
            break
        except Exception as e:
            print("bind port fails ", e, SERVER_IP)
            os.system('fuser -k -n tcp ' + str(port))
            time.sleep(3)
 
    while True:
        try:
            conn, client_addr = recv_socket.accept()
            recv_data(conn)
        except Exception as e:
            print(e)
 
for i in range(6):
    print("================",PORT_BASE + 2 * i)
    mp.Process(target=listen_client, args=(PORT_BASE + 2 * i,)).start()

到此這篇關(guān)于Python實現(xiàn)Windows端口監(jiān)聽程序的文章就介紹到這了,更多相關(guān)Python端口監(jiān)聽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論