检查网络连接

huangapple go评论82阅读模式
英文:

Check for Network 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?

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

得分: 2

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

不要检查。

只需尝试连接。如果连接失败,你会收到一个错误。根据该错误,你可以进行任何你想做的操作——重新尝试连接、尝试另一个服务器、退出程序或制作吐司。

例如,如果你使用标准的SSH库,代码可能如下所示:

cli := ssh.NewClient( ... )
conn, err := cli.Dial( ... )
if err != nil {
// 连接失败,所以做其他操作
}
英文:

> 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
}

huangapple
  • 本文由 发表于 2017年7月24日 17:13:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/45276599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定