Guest User

Untitled

a guest
Jan 5th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "log"
  6. "os"
  7. "io/ioutil"
  8. "golang.org/x/crypto/ssh"
  9. )
  10.  
  11. func main() {
  12. if len(os.Args) != 4 {
  13. log.Fatalf("Usage: %s <user> <host:port> <command>", os.Args[0])
  14. }
  15.  
  16. client, session, err := connectToHost(os.Args[1], os.Args[2])
  17. if err != nil {
  18. panic(err)
  19. }
  20. out, err := session.CombinedOutput("ls")
  21. if err != nil {
  22. panic(err)
  23. }
  24. fmt.Println(string(out))
  25. client.Close()
  26. }
  27.  
  28. func PublicKeyFile(file string) (ssh.AuthMethod, error) {
  29. buffer, err := ioutil.ReadFile(file)
  30. if err != nil {
  31. return nil, err
  32. }
  33.  
  34. key, err := ssh.ParsePrivateKey(buffer)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return ssh.PublicKeys(key), nil
  39. }
  40.  
  41. func connectToHost(user, host string) (*ssh.Client, *ssh.Session, error) {
  42. var pass string
  43. fmt.Print("Password: ")
  44. fmt.Scanf("%sn", &pass)
  45.  
  46. publicKey, err := PublicKeyFile(`./key.pem`)
  47. if err != nil {
  48. log.Println(err)
  49. }
  50.  
  51. sshConfig := &ssh.ClientConfig{
  52. User: user,
  53. Auth: []ssh.AuthMethod{publicKey},
  54. }
  55. sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()
  56.  
  57. client, err := ssh.Dial("tcp", host, sshConfig)
  58. if err != nil {
  59. return nil, nil, err
  60. }
  61.  
  62. session, err := client.NewSession()
  63. if err != nil {
  64. client.Close()
  65. return nil, nil, err
  66. }
  67.  
  68. return client, session, nil
  69. }
Add Comment
Please, Sign In to add comment