test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "time"
  7. "github.com/mitchellh/go-homedir"
  8. "golang.org/x/crypto/ssh"
  9. )
  10. func main() {
  11. sshHost := "119.28.163.42"
  12. sshUser := "root"
  13. sshPassword := ""
  14. sshType := "key" //password 或者 key
  15. sshKeyPath := "/root/.ssh/id_rsa" //ssh id_rsa.id 路径"
  16. sshPort := 7721
  17. //创建sshp登陆配置
  18. config := &ssh.ClientConfig{
  19. Timeout: time.Second, //ssh 连接time out 时间一秒钟, 如果ssh验证错误 会在一秒内返回
  20. User: sshUser,
  21. HostKeyCallback: ssh.InsecureIgnoreHostKey(), //这个可以, 但是不够安全
  22. //HostKeyCallback: hostKeyCallBackFunc(h.Host),
  23. }
  24. if sshType == "password" {
  25. config.Auth = []ssh.AuthMethod{ssh.Password(sshPassword)}
  26. } else {
  27. config.Auth = []ssh.AuthMethod{publicKeyAuthFunc(sshKeyPath)}
  28. }
  29. //dial 获取ssh client
  30. addr := fmt.Sprintf("%s:%d", sshHost, sshPort)
  31. sshClient, err := ssh.Dial("tcp", addr, config)
  32. if err != nil {
  33. log.Fatal("创建ssh client 失败", err)
  34. }
  35. defer sshClient.Close()
  36. //创建ssh-session
  37. session, err := sshClient.NewSession()
  38. if err != nil {
  39. log.Fatal("创建ssh session 失败", err)
  40. }
  41. defer session.Close()
  42. //执行远程命令
  43. combo, err := session.CombinedOutput("ifconfig")
  44. if err != nil {
  45. log.Fatal("远程执行cmd 失败", err)
  46. }
  47. log.Println("命令输出:", string(combo))
  48. }
  49. func publicKeyAuthFunc(kPath string) ssh.AuthMethod {
  50. //交叉编译打开文件
  51. keyPath, err := homedir.Expand(kPath)
  52. if err != nil {
  53. log.Fatal("find key's home dir failed", err)
  54. }
  55. //读文件
  56. key, err := ioutil.ReadFile(keyPath)
  57. if err != nil {
  58. log.Fatal("ssh key file read failed", err)
  59. }
  60. //解析为一个对象
  61. // Create the Signer for this private key.
  62. signer, err := ssh.ParsePrivateKey(key)
  63. if err != nil {
  64. log.Fatal("ssh key signer failed", err)
  65. }
  66. //放入key对象 生成一个指针
  67. return ssh.PublicKeys(signer)
  68. }