Azure在运行golang程序时出现get-credentials错误。

huangapple go评论135阅读模式
英文:

Azure get-credentials errors running in golang program

问题

我正在尝试使用以下脚本在Azure ACS Kubernetes中获取凭据:

  1. #! /bin/sh
  2. az login --service-principal --username=user -password=password --tenant=tenant
  3. az acs kubernetes get-credentials --resource-group=rg --name=acs1 --file=/tmp/kubeconfig.json --ssh-key-file=private.key --output=json --debug --verbose

在Mac命令行上运行该脚本可以正常工作。但是,当我尝试运行一个调用相同脚本的golang程序"cmd := exec.Command("/bin/sh", "-c", scriptName)"时,我会收到以下错误:

  1. No existing session
  2. Traceback (most recent call last):
  3. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/main.py", line 36, in main
  4. cmd_result = APPLICATION.execute(args)
  5. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/core/application.py", line 211, in execute
  6. result = expanded_arg.func(params)
  7. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 351, in __call__
  8. return self.handler(*args, **kwargs)
  9. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 555, in _execute_command
  10. reraise(*sys.exc_info())
  11. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 532, in _execute_command
  12. result = op(client, **kwargs) if client else op(**kwargs)
  13. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/command_modules/acs/custom.py", line 785, in k8s_get_credentials
  14. _k8s_get_credentials_internal(name, acs_info, path, ssh_key_file)
  15. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/command_modules/acs/custom.py", line 806, in _k8s_get_credentials_internal
  16. '.kube/config', path_candidate, key_filename=ssh_key_file)
  17. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/command_modules/acs/acs_client.py", line 62, in secure_copy
  18. ssh.connect(host, username=user, pkey=pkey)
  19. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/paramiko/client.py", line 394, in connect
  20. look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
  21. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/paramiko/client.py", line 649, in _auth
  22. raise saved_exception
  23. SSHException: No existing session

有什么想法吗?

英文:

I am trying to azure acs kubernetes credentials with the following script:

  1. #! /bin/sh
  2. az login --service-principal --username=user -password=password --tenant=tenant
  3. az acs kubernetes get-credentials --resource-group=rg --name=acs1 --file=/tmp/kubeconfig.json --ssh-key-file=private.key --output=json --debug --verbose

Running the script from command line on the mac works ok. When I try to run a golang program "cmd := exec.Command("/bin/sh", "-c", scriptName)" that calls the same script on the same computer I get the following error:

  1. No existing session
  2. Traceback (most recent call last):
  3. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/main.py", line 36, in main
  4. cmd_result = APPLICATION.execute(args)
  5. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/core/application.py", line 211, in execute
  6. result = expanded_arg.func(params)
  7. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 351, in __call__
  8. return self.handler(*args, **kwargs)
  9. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 555, in _execute_command
  10. reraise(*sys.exc_info())
  11. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 532, in _execute_command
  12. result = op(client, **kwargs) if client else op(**kwargs)
  13. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/command_modules/acs/custom.py", line 785, in k8s_get_credentials
  14. _k8s_get_credentials_internal(name, acs_info, path, ssh_key_file)
  15. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/command_modules/acs/custom.py", line 806, in _k8s_get_credentials_internal
  16. '.kube/config', path_candidate, key_filename=ssh_key_file)
  17. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/azure/cli/command_modules/acs/acs_client.py", line 62, in secure_copy
  18. ssh.connect(host, username=user, pkey=pkey)
  19. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/paramiko/client.py", line 394, in connect
  20. look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
  21. File "/Users/aarontorgerson/lib/azure-cli/lib/python2.7/site-packages/paramiko/client.py", line 649, in _auth
  22. raise saved_exception
  23. SSHException: No existing session

Any ideas?

答案1

得分: 0

根据您的描述和错误信息SSHException: No existing session,看起来您正在使用os/exec调用您的shell脚本文件,但失败了,因为命令az需要在ssh会话中的.azure路径下使用类似azureProfile.json的东西。

所以我建议您尝试使用下面的代码,使用golang.org/x/crypto/ssh包来实现。

以下是我认为与MacOS上相同的Linux示例代码:

  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "golang.org/x/crypto/ssh"
  12. )
  13. func getHostKey(host string) (ssh.PublicKey, error) {
  14. file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
  15. if err != nil {
  16. return nil, err
  17. }
  18. defer file.Close()
  19. scanner := bufio.NewScanner(file)
  20. var hostKey ssh.PublicKey
  21. for scanner.Scan() {
  22. fields := strings.Split(scanner.Text(), " ")
  23. if len(fields) != 3 {
  24. continue
  25. }
  26. if strings.Contains(fields[0], host) {
  27. var err error
  28. hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
  29. if err != nil {
  30. return nil, errors.New(fmt.Sprintf("error parsing %q: %v", fields[2], err))
  31. }
  32. break
  33. }
  34. }
  35. if hostKey == nil {
  36. return nil, errors.New(fmt.Sprintf("no hostkey for %s", host))
  37. }
  38. return hostKey, nil
  39. }
  40. func main() {
  41. hostKey, err := getHostKey("localhost")
  42. if err != nil {
  43. log.Fatal(err)
  44. }
  45. config := &ssh.ClientConfig{
  46. User: "peter",
  47. Auth: []ssh.AuthMethod{
  48. ssh.Password("peter ssh password"),
  49. },
  50. HostKeyCallback: ssh.FixedHostKey(hostKey),
  51. }
  52. // Dial your ssh server.
  53. conn, err := ssh.Dial("tcp", "localhost:22", config)
  54. if err != nil {
  55. log.Fatal("unable to connect: ", err)
  56. }
  57. defer conn.Close()
  58. session, err := conn.NewSession()
  59. if err != nil {
  60. log.Fatal("Failed to create session: ", err)
  61. }
  62. defer session.Close()
  63. // Once a Session is created, you can execute a single command on
  64. // the remote side using the Run method.
  65. var b bytes.Buffer
  66. session.Stdout = &b
  67. if err := session.Run("./test.sh"); err != nil {
  68. log.Fatal("Failed to run: " + err.Error())
  69. }
  70. fmt.Println(b.String())
  71. }

注意:在您的.ssh/known_hosts文件中,必须有像下面的内容一样的记录,针对localhost。如果没有,请先通过ssh登录以生成它,并将主机更改为localhost

  1. |localhost|qx8q1geNHGyRFp8Ttu+m2xY4OpU=|noyfrjpDRvtIzP2gzWEV77VZULo= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKXlyt/EFLnqwlNDimn73+wZVgCh3dhXi2YMWN6tHUj5LMirrUt0AtmQQVHex2b2ur79L5P6/L2J28NID569qAA=

希望对您有所帮助。

英文:

According to your description and the error information SSHException: No existing session, it sounds like you were using os/exec for calling your shell script file, but failed because command az needs to use something like azureProfile.json at the path .azure within a ssh session.

So I suggested you can try to use the code below with golang.org/x/crypto/ssh package to do it.

Here is my sample code for Linux which I think the same as on MacOS.

  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "golang.org/x/crypto/ssh"
  12. )
  13. func getHostKey(host string) (ssh.PublicKey, error) {
  14. file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
  15. if err != nil {
  16. return nil, err
  17. }
  18. defer file.Close()
  19. scanner := bufio.NewScanner(file)
  20. var hostKey ssh.PublicKey
  21. for scanner.Scan() {
  22. fields := strings.Split(scanner.Text(), " ")
  23. if len(fields) != 3 {
  24. continue
  25. }
  26. if strings.Contains(fields[0], host) {
  27. var err error
  28. hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
  29. if err != nil {
  30. return nil, errors.New(fmt.Sprintf("error parsing %q: %v", fields[2], err))
  31. }
  32. break
  33. }
  34. }
  35. if hostKey == nil {
  36. return nil, errors.New(fmt.Sprintf("no hostkey for %s", host))
  37. }
  38. return hostKey, nil
  39. }
  40. func main() {
  41. hostKey, err := getHostKey("localhost")
  42. if err != nil {
  43. log.Fatal(err)
  44. }
  45. config := &ssh.ClientConfig{
  46. User: "peter",
  47. Auth: []ssh.AuthMethod{
  48. ssh.Password("peter ssh password"),
  49. },
  50. HostKeyCallback: ssh.FixedHostKey(hostKey),
  51. }
  52. // Dial your ssh server.
  53. conn, err := ssh.Dial("tcp", "localhost:22", config)
  54. if err != nil {
  55. log.Fatal("unable to connect: ", err)
  56. }
  57. defer conn.Close()
  58. session, err := conn.NewSession()
  59. if err != nil {
  60. log.Fatal("Failed to create session: ", err)
  61. }
  62. defer session.Close()
  63. // Once a Session is created, you can execute a single command on
  64. // the remote side using the Run method.
  65. var b bytes.Buffer
  66. session.Stdout = &b
  67. if err := session.Run("./test.sh"); err != nil {
  68. log.Fatal("Failed to run: " + err.Error())
  69. }
  70. fmt.Println(b.String())
  71. }

Notes: There must be a record like the content below for localhost in your .ssh/known_hosts file. If not, you can first login via ssh to generate it and change the host with localhost.

> |localhost|qx8q1geNHGyRFp8Ttu+m2xY4OpU=|noyfrjpDRvtIzP2gzWEV77VZULo= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKXlyt/EFLnqwlNDimn73+wZVgCh3dhXi2YMWN6tHUj5LMirrUt0AtmQQVHex2b2ur79L5P6/L2J28NID569qAA=

Hope it helps.

huangapple
  • 本文由 发表于 2017年8月22日 06:26:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/45806377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定