ssh.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package remote
  14. import (
  15. "flag"
  16. "fmt"
  17. "os/exec"
  18. "os/user"
  19. "strings"
  20. "sync"
  21. "k8s.io/klog"
  22. )
  23. var sshOptions = flag.String("ssh-options", "", "Commandline options passed to ssh.")
  24. var sshEnv = flag.String("ssh-env", "", "Use predefined ssh options for environment. Options: gce")
  25. var sshKey = flag.String("ssh-key", "", "Path to ssh private key.")
  26. var sshUser = flag.String("ssh-user", "", "Use predefined user for ssh.")
  27. var sshOptionsMap map[string]string
  28. var sshDefaultKeyMap map[string]string
  29. func init() {
  30. usr, err := user.Current()
  31. if err != nil {
  32. klog.Fatal(err)
  33. }
  34. sshOptionsMap = map[string]string{
  35. "gce": "-o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o CheckHostIP=no -o StrictHostKeyChecking=no -o ServerAliveInterval=30 -o LogLevel=ERROR",
  36. }
  37. sshDefaultKeyMap = map[string]string{
  38. "gce": fmt.Sprintf("%s/.ssh/google_compute_engine", usr.HomeDir),
  39. }
  40. }
  41. var hostnameIPOverrides = struct {
  42. sync.RWMutex
  43. m map[string]string
  44. }{m: make(map[string]string)}
  45. // AddHostnameIP adds <hostname,ip> pair into hostnameIPOverrides map.
  46. func AddHostnameIP(hostname, ip string) {
  47. hostnameIPOverrides.Lock()
  48. defer hostnameIPOverrides.Unlock()
  49. hostnameIPOverrides.m[hostname] = ip
  50. }
  51. // GetHostnameOrIP converts hostname into ip and apply user if necessary.
  52. func GetHostnameOrIP(hostname string) string {
  53. hostnameIPOverrides.RLock()
  54. defer hostnameIPOverrides.RUnlock()
  55. host := hostname
  56. if ip, found := hostnameIPOverrides.m[hostname]; found {
  57. host = ip
  58. }
  59. if *sshUser != "" {
  60. host = fmt.Sprintf("%s@%s", *sshUser, host)
  61. }
  62. return host
  63. }
  64. // getSSHCommand handles proper quoting so that multiple commands are executed in the same shell over ssh
  65. func getSSHCommand(sep string, args ...string) string {
  66. return fmt.Sprintf("'%s'", strings.Join(args, sep))
  67. }
  68. // SSH executes ssh command with runSSHCommand as root. The `sudo` makes sure that all commands
  69. // are executed by root, so that there won't be permission mismatch between different commands.
  70. func SSH(host string, cmd ...string) (string, error) {
  71. return runSSHCommand("ssh", append([]string{GetHostnameOrIP(host), "--", "sudo"}, cmd...)...)
  72. }
  73. // SSHNoSudo executes ssh command with runSSHCommand as normal user. Sometimes we need this,
  74. // for example creating a directory that we'll copy files there with scp.
  75. func SSHNoSudo(host string, cmd ...string) (string, error) {
  76. return runSSHCommand("ssh", append([]string{GetHostnameOrIP(host), "--"}, cmd...)...)
  77. }
  78. // runSSHCommand executes the ssh or scp command, adding the flag provided --ssh-options
  79. func runSSHCommand(cmd string, args ...string) (string, error) {
  80. if *sshKey != "" {
  81. args = append([]string{"-i", *sshKey}, args...)
  82. } else if key, found := sshDefaultKeyMap[*sshEnv]; found {
  83. args = append([]string{"-i", key}, args...)
  84. }
  85. if env, found := sshOptionsMap[*sshEnv]; found {
  86. args = append(strings.Split(env, " "), args...)
  87. }
  88. if *sshOptions != "" {
  89. args = append(strings.Split(*sshOptions, " "), args...)
  90. }
  91. output, err := exec.Command(cmd, args...).CombinedOutput()
  92. if err != nil {
  93. return string(output), fmt.Errorf("command [%s %s] failed with error: %v", cmd, strings.Join(args, " "), err)
  94. }
  95. return string(output), nil
  96. }