You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用批处理从TXT读取变量生成MTPuTTY导入XML并按用户分文件?

解决MTPuTTY XML批量生成(含按用户拆分)的问题

先帮你梳理下原批处理里的核心问题:文件名带空格没加引号导致识别错误、</>这类特殊字符没转义触发语法报错,还有FOR循环的多行输出语法不规范。下面分两种场景给你提供解决方案:

基础版:生成单个整合XML文件

修正后的批处理代码,能把所有连接字符串转成对应XML节点并写入同一个文件:

@echo off
setlocal enabledelayedexpansion

:: 清空已有目标文件(如果存在)
if exist "connection strings.xml" del "connection strings.xml"

:: 遍历每个连接字符串
for /f "delims=" %%i in ("connection strings.txt") do (
    echo ^<Node Type="1"^>>>"connection strings.xml"
    echo   ^<SavedSession^>%%i^</SavedSession^>>>"connection strings.xml"
    echo   ^<DisplayName^>%%i^</DisplayName^>>>"connection strings.xml"
    echo   ^<ServerName^>%%i^</ServerName^>>>"connection strings.xml"
    echo   ^<PuttyConType^>0^</PuttyConType^>>>"connection strings.xml"
    echo   ^<Port^>22^</Port^>>>"connection strings.xml"
    echo   ^<UserName^>^</UserName^>>>"connection strings.xml"
    echo   ^<Password^>^</Password^>>>"connection strings.xml"
    echo   ^<PasswordDelay^>0^</PasswordDelay^>>>"connection strings.xml"
    echo   ^<CLParams^>-load %%i "%%i" -P 22^</CLParams^>>>"connection strings.xml"
    echo   ^<ScriptDelay^>0^</ScriptDelay^>>>"connection strings.xml"
    echo ^</Node^>>>"connection strings.xml"
    echo.>>>"connection strings.xml" :: 空行分隔节点,提升可读性
)

echo XML文件生成完成!
pause

进阶版:按用户生成单独XML文件

要实现按用户拆分,我们需要先从username@server格式中提取用户名,再将对应节点写入以用户名为标识的文件:

@echo off
setlocal enabledelayedexpansion

:: 可选:清空之前生成的用户XML文件
for %%f in (*_mtputty.xml) do del %%f

:: 遍历每个连接字符串
for /f "delims=" %%i in ("connection strings.txt") do (
    :: 用@作为分隔符,提取@前的用户名部分
    for /f "delims=@ tokens=1" %%u in ("%%i") do (
        set "user_file=%%u_mtputty.xml"
        :: 写入对应节点到用户专属文件
        echo ^<Node Type="1"^>>>!user_file!
        echo   ^<SavedSession^>%%i^</SavedSession^>>>!user_file!
        echo   ^<DisplayName^>%%i^</DisplayName^>>>!user_file!
        echo   ^<ServerName^>%%i^</ServerName^>>>!user_file!
        echo   ^<PuttyConType^>0^</PuttyConType^>>>!user_file!
        echo   ^<Port^>22^</Port^>>>!user_file!
        echo   ^<UserName^>^</UserName^>>>!user_file!
        echo   ^<Password^>^</Password^>>>!user_file!
        echo   ^<PasswordDelay^>0^</PasswordDelay^>>>!user_file!
        echo   ^<CLParams^>-load %%i "%%i" -P 22^</CLParams^>>>!user_file!
        echo   ^<ScriptDelay^>0^</ScriptDelay^>>>!user_file!
        echo ^</Node^>>>!user_file!
        echo.>>>!user_file!
    )
)

echo 按用户拆分XML文件完成!
pause

关键细节解释

  • ^</^>:<和>是批处理的重定向命令,必须用^转义才能作为普通XML标签输出
  • "delims=":确保读取完整的连接字符串,避免因潜在空格截断内容
  • tokens=1:拆分用户名时,仅提取@符号前的第一部分作为用户名标识
  • enabledelayedexpansion:保证循环中动态变量!user_file!能正确解析,不会提前变成空值
  • 用户文件命名:最终生成的文件会是用户名_mtputty.xml格式,比如username1_mtputty.xml

内容的提问来源于stack exchange,提问作者Moominboy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:48:13