2017-07-18 70 views
-1

我有一個for循環,它將通過SSH連接到服務器,殺死一些進程。我遇到的問題是,我的程序在所有進程(包括SSH)被終止後都會嘗試重新連接到服務器,這將不起作用。該程序崩潰。3秒後關閉SSH會話

如何在3秒後關閉ssh連接並使用for循環繼續?

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

回答

0

我不知道你使用,但根據您的代碼,它可以this

爲了避免您需要檢查,如果ssh連接成功建立的程序崩潰是什麼SSH 11b是。要做到由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") 
} 
0

有一點從喜歡哪個軟件包正在使用等您發佈的代碼..失蹤。但是正如我提供的代碼示例使用了上下文包添加3秒超時。您可以根據自己的喜好進行修改,但我認爲這裏使用上下文非常合適。如果你從未使用過它們,請參閱標準庫文檔here,並進行一些Google搜索以獲取更多示例。

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