登录
首页 >  Golang >  Go问答

使用 crypto/ssh 和 golang 运行 iperf3

来源:stackoverflow

时间:2024-03-16 19:00:31 111浏览 收藏

使用 Golang 运行 iperf3 测量虚拟机之间的吞吐量时,手动流程可以顺利执行。然而,在 Golang 代码中,代码在执行 `CombinedOutput` 函数时挂起,导致 iperf3 无法正常运行。文章探讨了这个问题,并提供了解决方案,以解决 iperf3 在服务器端运行时遇到的特定挑战。

问题内容

目标

使用 golang 的 crypto/ssh 在两个虚拟机上运行 iperf3 来测量吞吐量。

手动流程

以下是有效的手动流程的描述。我正在尝试在 golang 中做同样的事情。

手动方法:从 jumpbox 连接到 vm1 并以 server 身份运行 iperf

# login to vm1
ssh [email protected]
# run iperf server on vm1
iperf3 -s -p 5001

从上图中您可以看到服务器正在那里监听。相同的命令会挂起 golang 代码,如下所述。

手动方法:从 jumpbox 连接到 vm2 并以 client 身份运行 iperf

# login to vm2
ssh [email protected]

# run client tests on vm2
iperf3 -c 168.61.222.12 -p 5001 -i 1 -t 3

所有这些都可以通过命令行运行得很好。下面是使用 golang 的说明,但代码挂起。

问题:golang 代码挂起

golang 代码挂在下面一行。查看函数:

putvm1intoservermode()

代码挂起:

putvm1intoservermode() {}
    # code hangs here
    out, err := 
      vmconnectserver.hostsession.combinedoutput(vmconnectserver.commands[0])
      ...
}

由于您在手动过程中看到的内容,这是预期的:

主要代码

type VMCONNECT struct {
    hostConnection *ssh.Client
    hostSession    *ssh.Session
    user           string
    hostPort       string
    commands       []string
    password       string
}

var VMConnectServer = VMCONNECT{
    nil,
    nil,
    "testadmin",
    "169.61.222.12:22",
    []string{"iperf3 -s -p 5001"},
    "????",
}
/*************************************
Logic
  connect to server
  put vm into server mode
  connect to client
  run iperf3 tests
  close client
  close server
**************************************/

func main() {

    connectToServer()
    putVM1IntoServerMode()
    // other code ommitted for brevity
}    

# This works fine, no issues
func connectToServer() {
    var err error
    VMConnectServer.hostConnection, VMConnectServer.hostSession, err = connectToHost(VMConnectServer.user, VMConnectServer.hostPort)
    if err != nil {
        panic(err)
    }
}

# Code hangs here
func putVM1IntoServerMode() {
    # Code hangs here
    out, err := VMConnectServer.hostSession.CombinedOutput(VMConnectServer.commands[0])
    if err != nil {
        panic(err)
    }
    fmt.Println(string(out))
}

如何解决

我是否使用通道异步运行代码? 解决这个问题的最佳方法是什么?

感谢任何指导。


解决方案


成功!

当在iperf的服务器端运行时,这是非常棘手的。

func runIperfTestsFromVM2() string {
    fmt.Println(VMConnectClient.commands[0])
    out, err := VMConnectClient.hostSession.CombinedOutput("sh -c 'nohup iperf3 -s -p 5001 > /dev/null 2>&1 &'")
    if err != nil {
        panic(err)
    }
    fmt.Println(string(out))
    return string(out)
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>