152 字
1 分钟
自动发送本机IP和MAC脚本
2025-10-08

前言#

学校资产乱,为了更好的登记,因此利用AI写了个脚本,也在这边分享开源

使用说明#

  • 客户端运行后,根据提示输入服务端的ip和端口号
  • 服务端使用前请先安装好python
  • 客户端和服务端使用之前最好把防火墙停用
  • 客户端最好把WMIC先安装好,虽然脚本已经有安装脚步,但是也是建议先安装好WMIC
  • 收集到的信息会在当前目录下的received_device_info文件夹下

服务端#

import http.server
import socketserver
import os
import datetime
# 设置服务器端口
PORT = 5400
# 创建接收文件夹
RECEIVE_FOLDER = "received_device_info"
if not os.path.exists(RECEIVE_FOLDER):
os.makedirs(RECEIVE_FOLDER)
class MyHttpRequestHandler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
# 获取请求头中的内容长度
content_length = int(self.headers['Content-Length'])
# 读取请求体中的数据
post_data = self.rfile.read(content_length).decode('utf-8')
# 获取当前时间戳,用于生成唯一的文件名
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
# 从数据中提取计算机名(如果有的话)
computer_name = "unknown"
for line in post_data.split('\n'):
if "计算机名:" in line:
computer_name = line.split(":")[1].strip().replace(' ', '_').replace('\\', '_').replace('/', '_')
break
# 创建文件名
file_name = f"{RECEIVE_FOLDER}/device_info_{computer_name}_{timestamp}.txt"
# 保存接收到的数据到文件
with open(file_name, 'w', encoding='utf-8') as f:
f.write(post_data)
# 打印接收到的信息
print(f"\n[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 接收到新的设备信息:")
print(f"- 保存文件: {file_name}")
print(f"- 数据内容:")
print(post_data)
print("=" * 50)
# 发送响应
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("数据已成功接收并保存".encode('utf-8'))
def do_GET(self):
# 简单的GET请求处理,用于验证服务器是否运行
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
response = f"""
<html>
<head><title>设备信息接收服务器</title></head>
<body>
<h1>设备信息接收服务器</h1>
<p>服务器正在运行中,等待接收设备信息...</p>
<p>接收的文件保存在: {RECEIVE_FOLDER}</p>
</body>
</html>
"""
self.wfile.write(response.encode('utf-8'))
# 创建HTTP服务器实例
handler_object = MyHttpRequestHandler
httpd = socketserver.TCPServer(('', PORT), handler_object)
# 打印服务器启动信息
print(f"\n设备信息接收服务器启动成功!")
print(f"服务器地址: http://0.0.0.0:{PORT}")
print(f"接收的文件将保存在: {RECEIVE_FOLDER}")
print(f"请在发送设备上运行 send_ip_mac.bat 脚本")
print("=" * 50)
print("按 Ctrl+C 停止服务器")
print("=" * 50)
# 开始监听HTTP请求
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\n服务器已停止")
httpd.server_close()

客户端#

@echo off
setlocal enabledelayedexpansion
:: Check if WMIC is available and install if not
echo Checking WMIC availability...
:: Test WMIC command directly
wmic os get caption >nul 2>&1
if %errorlevel% neq 0 (
echo WMIC is not available. Attempting to install...
:: Try to install WMIC using DISM
dism /Online /Add-Capability /CapabilityName:WMIC~~~~ >nul 2>&1
:: Check if installation was successful
wmic os get caption >nul 2>&1
if %errorlevel% neq 0 (
echo ERROR: Failed to install WMIC. Please run this script as Administrator.
pause
exit /b 1
) else (
echo SUCCESS: WMIC has been installed successfully.
)
) else (
echo WMIC is available.
)
echo.
:: Let user input target IP and port
set /p TARGET_IP=Enter receiver IP address [Default: 10.80.62.175]:
if "%TARGET_IP%"=="" set TARGET_IP=10.80.62.175
set /p TARGET_PORT=Enter receiver port [Default: 5400]:
if "%TARGET_PORT%"=="" set TARGET_PORT=5400
set "OUTPUT_DIR=%TEMP%"
set "OUTPUT_FILE=%OUTPUT_DIR%\device_info_%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt"
:: Replace spaces with zeros in time
set OUTPUT_FILE=%OUTPUT_FILE: =0%
echo.
echo ===== IP and MAC Address Collector =====
echo.
echo Target Server: %TARGET_IP%:%TARGET_PORT%
echo.
:: Create output file with header
echo ========================================= > "%OUTPUT_FILE%"
echo DEVICE INFORMATION REPORT >> "%OUTPUT_FILE%"
echo Generated: %date% %time% >> "%OUTPUT_FILE%"
echo ========================================= >> "%OUTPUT_FILE%"
echo. >> "%OUTPUT_FILE%"
:: Collect network adapter information with MAC and IP association
echo Collecting network adapter information...
echo [NETWORK ADAPTERS] >> "%OUTPUT_FILE%"
echo.
:: Directly capture ipconfig /all output for complete network information
echo "Complete network adapter information (including MAC and IP addresses):" >> "%OUTPUT_FILE%"
echo. >> "%OUTPUT_FILE%"
:: Append ipconfig /all output to the report
ipconfig /all >> "%OUTPUT_FILE%"
echo. >> "%OUTPUT_FILE%"
echo "To determine which MAC address corresponds to which IP address:" >> "%OUTPUT_FILE%"
echo "1. Look for the network adapter you're interested in (e.g., Ethernet adapter, Wireless LAN adapter)" >> "%OUTPUT_FILE%"
echo "2. In the same adapter section, you'll find both Physical Address (MAC) and IPv4 Address" >> "%OUTPUT_FILE%"
echo "3. These values are associated with the same network adapter" >> "%OUTPUT_FILE%"
echo. >> "%OUTPUT_FILE%"
set "ip_found=true"
echo. >> "%OUTPUT_FILE%"
:: Collect System Information
echo [SYSTEM INFO] >> "%OUTPUT_FILE%"
for /f "tokens=2 delims==" %%b in ('wmic computersystem get name /value') do (
echo Computer Name: %%b >> "%OUTPUT_FILE%"
echo Computer Name: %%b
)
for /f "tokens=2 delims==" %%c in ('wmic os get caption /value') do (
echo OS: %%c >> "%OUTPUT_FILE%"
echo OS: %%c
)
echo. >> "%OUTPUT_FILE%"
echo ========================================= >> "%OUTPUT_FILE%"
:: Add warning only if no IP found
if not defined ip_found (
echo WARNING: No IPv4 addresses found! >> "%OUTPUT_FILE%"
echo WARNING: No IPv4 addresses found!
)
echo.
echo Report saved to: %OUTPUT_FILE%
echo.
:: Create PowerShell script in current directory
set "PS_SCRIPT=send_device_info.ps1"
echo Creating PowerShell script in current directory...
echo # Script to send device information > "%PS_SCRIPT%"
echo $fileContent = Get-Content -Path "%OUTPUT_FILE%" -Raw >> "%PS_SCRIPT%"
echo $targetUrl = "http://%TARGET_IP%:%TARGET_PORT%" >> "%PS_SCRIPT%"
echo Write-Host "Sending data to $targetUrl..." >> "%PS_SCRIPT%"
echo try { >> "%PS_SCRIPT%"
echo $webClient = New-Object System.Net.WebClient >> "%PS_SCRIPT%"
echo $webClient.Encoding = [System.Text.Encoding]::UTF8 >> "%PS_SCRIPT%"
echo $response = $webClient.UploadString($targetUrl, $fileContent) >> "%PS_SCRIPT%"
echo Write-Host "SUCCESS: Data sent successfully!" >> "%PS_SCRIPT%"
echo } catch { >> "%PS_SCRIPT%"
echo Write-Host "ERROR: Failed to send data: $($_.Exception.Message)" >> "%PS_SCRIPT%"
echo Write-Host "Please ensure receiving server is running on %TARGET_IP%:%TARGET_PORT%" >> "%PS_SCRIPT%"
echo } >> "%PS_SCRIPT%"
echo pause >> "%PS_SCRIPT%"
:: Verify script was created
dir "%PS_SCRIPT%" >nul 2>&1
if errorlevel 1 (
echo WARNING: Failed to create PowerShell script, but will continue...
) else (
echo.
echo Attempting to send data to %TARGET_IP%:%TARGET_PORT%...
powershell.exe -ExecutionPolicy Bypass -File "%PS_SCRIPT%"
del "%PS_SCRIPT%" >nul 2>&1
)
:: Clean up temporary files
del "%PS_SCRIPT%" >nul 2>&1
del "%OUTPUT_FILE%" >nul 2>&1
echo.
echo ===== Operation Completed =====
echo.
echo Press any key to exit...
pause >nul
endlocal
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

自动发送本机IP和MAC脚本
https://vtdd.vip/posts/自动发送本机ip和mac脚本/
作者
浮生
发布于
2025-10-08
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录