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