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