go - 检查网络连接

标签 go ssh connection

在运行程序之前如何检查我是否能够通过 ssh 连接到服务器?

这是我连接到服务器的方式: cli := ssh.NewSSHClient(conf.User, randomServer)

我想使用 switch 或 if 语句,例如:

switch cli := ssh.NewSSHClient(conf.User, randomServer) {
case successful:
    fmt.Println("Good morning!")
case fail:
    fmt.Println("Good afternoon.")
}

建立连接:

func NewSSHClient(user string, hostname string) *SSHClient{
  sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
  if err != nil {
    logrus.Fatal(err)
  }

  agent := agent.NewClient(sock)
  signers, err := agent.Signers()
  if err != nil {
    logrus.Fatal(err)
  }
  auths := []ssh.AuthMethod{ssh.PublicKeys(signers...)}
  cfg := &ssh.ClientConfig{
    User: user,
    Auth: auths,
    HostKeyCallback: ssh.InsecureIgnoreHostKey(),

  }
  cfg.SetDefaults()

  return &SSHClient{
    User: user,
    Hostname: hostname,
    Config: cfg,
  }
}

// Use one connection per command.
// Catch in the client when required.
func (cli *SSHClient)ExecuteCmd(command string){
  conn, err := ssh.Dial("tcp", cli.Hostname+":22", cli.Config)
  if err!=nil {
    logrus.Infof("%s@%s", cli.Config.User, cli.Hostname)
    logrus.Info("Hint: Add you key to the ssh agent: 'ssh-add ~/.ssh/id_rsa'")
    logrus.Fatal(err)
  }
  session, _ := conn.NewSession()
  defer session.Close()
  var stdoutBuf bytes.Buffer
  session.Stdout = &stdoutBuf
  err = session.Run(command)
  if err != nil {
    logrus.Fatalf("Run failed:%v", err)
  }
  logrus.Infof(">%s", stdoutBuf.Bytes())
}

最佳答案

How can I check if I am able to connect to a server via ssh before running a program on it?

不要。

只需尝试连接。如果它不起作用,您将收到错误消息。基于该错误,您可以做任何您想做的事情——重试连接、尝试另一台服务器、退出程序或 toast 。

如果您要使用标准 SSH 库,例如它看起来像这样:

cli := ssh.NewClient( ... )
conn, err := cli.Dial( ... )
if err != nil {
    // The connection failed, so do something else
}

关于go - 检查网络连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45276599/

相关文章:

go - golang如何检查变量是否为零

go - 检查结构字段是否为空

使用 testcontainer-go 时遇到问题

jenkins - root用户和jenkins有什么区别?

ruby - RVM 无法通过 SSH 工作(作为一项功能)

linux - 循环 SSH 隧道

GoMobile 版本 : Cannot find package

azure - MS Azure 数据工厂 ADF 从 BLOB 到 Azure Postgres Gen5 8 核心的复制事件失败,连接因主机错误而关闭

php - 使用 PHP 从 mySQL 获取记录并将其发送到 VB.net

connection - 我可以关闭ATS并将应用程序上传到App Store吗? -iOS 9