【问题标题】:Batch file, Need to save output to text file for telnet command in windows批处理文件,需要将输出保存到文本文件中,以便在 windows 中使用 telnet 命令
【发布时间】:2017-05-30 19:19:49
【问题描述】:

我正在尝试远程登录端口并希望将输出保存到文本文件中。我已经查看并获得了两种解决方案,但它们都没有通过命令提示符为我工作。

telnet 127.0.0.1 7000 -f output.txt

telnet 127.0.0.1 7000 >> output.txt

另外,用 1> 和 2> 分别检查了这个 link 的 stdout 和 stderr。还尝试通过此链接中提到的 2>&1 将 2 (stderr) 重定向到 1 (stdout)。

在批处理文件中运行以下代码后,文件没有任何日志。但如果它能够远程登录端口,它就会存储日志。但我的要求是如果 telnet 无法连接,则从 cmd 获取日志,如下所示:

连接到 127.0.0.1...无法在端口 7002 上打开与主机的连接:连接失败

for port in 7000 7001 7002 
 do
  start cmd.exe /k "telnet 127.0.0.1  $port -f C:\Users\rohit.bagjani\Desktop\result\telnetresult.txt"
done

【问题讨论】:

  • 你无法像这样捕获内置的 telnet 客户端输出。 MS telnet 不支持标准输入/输出。最好考虑第三方 telnet 客户端或使用带有 powershell/c# 的套接字
  • 您在代码中显示的 for port 部分永远不会在 Windows 中工作,这些是 Unix/Linux 命令。此外,-f 将仅在 telnet 上记录客户端 telnet 错误...不过,您是否想纯粹为了端口测试而运行它?
  • 感谢@npocmaka 的评论。
  • @GerhardBarnard for 循环在 Windows 中确实有效,是的,我已经提到了您的观点(以不同的方式) -f 只会记录客户端 telnet 错误。是的,我只想为端口测试做这个。你有什么解决方法吗,那真的很有帮助吗?
  • 是的,使用 powershell。将发布答案。

标签: windows batch-file cmd


【解决方案1】:

以管理员身份打开 cmd.exe 并运行:

powershell set-executionpolicy Bypass

创建一个新文件并将其命名为port-test.ps1

把这个粘贴进去。

param(
    [string] $rHost = $1,
    [int] $port = $2
     )

   write-host "Connecting to $rHost on port $port"
try {
  $socket = new-object System.Net.Sockets.TcpClient($rHost, $port)
} catch [Exception] {
  write-host $_.Exception.GetType().FullName
  write-host $_.Exception.Message
  exit 1
}

write-host "Connected.`n"
exit 0

现在您可以打开 cmd.exe 并像这样运行它:

powershell -file D:\test\port-test.ps1 hostnamename portnr

即 powershell -file D:\test\telnetit.ps1 somehost.domain.com 23

如果连接不起作用,您将收到如下消息:

Connecting to somehost.domain.com on port 23 system.Management.Automation.MethodInvocationException Exception calling ".ctor" with "2" argument(s): "No connection could be made because the target machine actively refused it 10.1.2.3:23"

如果成功了,你会得到:

Connecting to somehost.domain.com on port 23 Connected.

【讨论】:

  • 我有这个解决方案,我正在寻找解决方案直接让批处理文件运行命令行。无论如何,谢谢。
  • 对于批处理可以等待超时和回显失败,如果无法连接或回显连接,但这是一种更可靠的方法。
猜你喜欢
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 2015-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多