package main import ( "flag" "fmt" "golang.org/x/crypto/ssh" "os/user" "strconv" ) var currentUser string func init() { user, err := user.Current() if err != nil { currentUser = "root" return } currentUser = user.Username } func main() { host := flag.String("h", "", "server host ip") port := flag.Int("p", 22, "sshd port") user := flag.String("u", currentUser, "sshd username") password := flag.String("p", "", "sshd password") cmd := flag.String("c", "ls", "sshd command") flag.Parse() sshClient, err := getClient(*host, *port, *user, *password) if err != nil { fmt.Println(err) return } defer sshClient.Close() res, err := SSH(sshClient, *cmd) if err != nil { fmt.Println(err) return } fmt.Println(res) } func getClient(host string, port int, username, password string) (*ssh.Client, error) { config := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.Password(password), }, HostKeyCallback: ssh.InsecureIgnoreHostKey(), // 忽略主机密钥验证 } client, err := ssh.Dial("tcp", host+":"+strconv.Itoa(port), config) if err != nil { return nil, err } return client, nil } func SSH(sshClient *ssh.Client, cmd string) (string, error) { session, err := sshClient.NewSession() if err != nil { return "", err } defer session.Close() var b []byte b, err = session.CombinedOutput(cmd) if err != nil { return "", err } return string(b), nil }