golang: sshkit 使用指南
一个 golang 使用库
基本代码
- sshkit
- goph
package main
import (
"github.com/zhiminwen/magetool/sshkit"
)
func main() {
client, _ := sshkit.NewSSHClient("8.153.96.239", "22", "root", "PASSWORD", "")
client.Execute("id; hostname")
}
另一个
推荐一个
goph
更好用。
package main
import (
"fmt"
"log"
"os"
"github.com/melbahja/goph"
)
func main() {
// Start new ssh connection with private key.
homedir := os.Getenv("HOME")
idrsa := fmt.Sprintf("%s/.ssh/id_rsa", homedir)
auth, err := goph.Key(idrsa, "")
if err != nil {
log.Fatal(err)
}
client, err := goph.New("root", "8.153.96.239", auth)
if err != nil {
log.Fatal(err)
}
// Defer closing the network connection.
defer client.Close()
// Execute your command.
out, err := client.Run("id; hostname")
if err != nil {
log.Fatal(err)
}
// Get your output as []byte.
fmt.Println(string(out))
}