duanbiaoshu2021 2017-07-24 09:13
浏览 60

检查网络连接

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

This is how I am connecting to a server: cli := ssh.NewSSHClient(conf.User, randomServer)

and I would like to either use switch or an if statement like:

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

establish connection:

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())
}
  • 写回答

1条回答 默认 最新

  • duanlanqian9974 2017-07-24 09:21
    关注

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

    Don't.

    Just attempt the connection. If it doesn't work, you'll get an error. Based on that error, you can do whatever you want--retry the connection, try another server, exit the program, or make toast.

    If you were to use the standard SSH library, for instance it would look something like this:

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

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码