I have a for loop which will connect to a server via SSH, kill some processes. The issue that I am running into is that my program tries to reconnect to the server after killing all processes (including SSH) which won't work. The program crashes.
How can I close the ssh connection after 3 seconds and move on with the for loop?
for i := 0; i < 900; i++ {
// pick random number
randomServer := fmt.Sprint(serverList[rand.Intn(len(serverList))])
// print info
logrus.Warn("Loop: ", i)
logrus.Warn("Connecting to: ", randomServer)
// connect to server
cli := ssh.NewSSHClient("root", randomServer)
// execute any command
cli.ExecuteCmd("killall5")
cli.ExecuteCmd("exit")
}
I don't know what ssh lib are you using but based on your code it can be this
To avoid program crash you need to check if ssh connection was established successfully. To do this check error produced by ssh.NewSSHClient
for i := 0; i < 900; i++ {
// pick random number
randomServer := fmt.Sprint(serverList[rand.Intn(len(serverList))])
// print info
logrus.Warn("Loop: ", i)
logrus.Warn("Connecting to: ", randomServer)
// connect to server
cli, err := ssh.NewSSHClient("root", randomServer)
if err != nil {
fmt.Println(err)
continue;
}
// execute any command
cli.ExecuteCmd("killall5")
cli.ExecuteCmd("exit")
}
There is a bit missing from the code you posted.. Like which packages are being used etc.. however as an example I've provide code that uses the context package to add a 3 second timeout. You can modify this as you see fit, but I think the use of context is very appropriate here. If you've never used them see the standard library docs here and do some googling for more examples.
// whatever this is
var serverList []string
func serverStuff(ctx context.Context, loop int, server string) {
// print info
logrus.Warn("Loop: ", loop)
logrus.Warn("Connecting to: ", server)
// connect to server
cli := ssh.NewSSHClient("root", server)
// execute any command
cli.ExecuteCmd("killall5")
return
}
func main() {
for i := 0; i < 900; i++ {
// pick random number
// create a context that waits 3 seconds
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
randomServer := fmt.Sprint(serverList[rand.Intn(len(serverList))])
go serverStuff(ctx, i, randomServer)
for {
select {
case <-ctx.Done(): // 3 seconds have passed break this loop bring us back to the top
break
}
}
}
}