golang ssh远程执行命令
时间: 2023-06-30 22:05:33 浏览: 99
使用 Golang 的 `ssh` 包可以实现 SSH 远程执行命令。下面是一个简单的示例代码:
```go
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"golang.org/x/crypto/ssh"
)
func main() {
host := "example.com"
user := "username"
password := "password"
command := "ls -l"
// 创建 SSH 连接
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", host+":22", config)
if err != nil {
log.Fatal("Failed to dial: ", err)
}
defer client.Close()
// 创建 SSH 会话
session, err := client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
defer session.Close()
// 执行命令
output, err := session.Output(command)
if err != nil {
log.Fatal("Failed to execute command: ", err)
}
fmt.Println(string(output))
}
```
在使用前请先安装 `golang.org/x/crypto/ssh` 包。
以上代码创建了一个 SSH 连接,并在远程主机上执行了 `ls -l` 命令,并返回了命令的输出结果。你可以将 `command` 变量改为你需要执行的任何命令。