【go】初学golang,想试试ssh,编译通过了,但是运行报错,大侠搭救下. T_T

package main

import (

"bytes"

"fmt"

"golang.org/x/crypto/ssh"

)

func tryConnect(user, addr string) (client *ssh.Client) {

config := &ssh.ClientConfig{

User: user,

Auth: []ssh.AuthMethod{ssh.Password("passw0rd")},

}

client, _ = ssh.Dial("tcp", addr, config)

return

}

func runCmd(client *ssh.Client, cmd string) (stdout string, err error) {

session, err := client.NewSession()

if err != nil {

return

}

var buf bytes.Buffer

session.Stdout = &buf

err = session.Run(cmd)

if err != nil {

return

}

stdout = string(buf.Bytes())

defer session.Close()

return

}

func main() {

start := tryConnect("root", "127.0.0.1")

fmt.Printf(runCmd(start, "cat /proc/loadavg"))

}

报错:

runtime error: invalid memory address or nil pointer dereference

goroutine 1 [running]:

golang.org/x/crypto/ssh.(*Client).NewSession(0x0, 0x400d75, 0x0, 0x0)

/root/go/src/golang.org/x/crypto/ssh/client.go:129 +0x132

main.runCmd(0x0, 0x63eb90, 0x11, 0x0, 0x0, 0x0, 0x0)

/root/tmp/ssh.go:19 +0x8e

main.main()

/root/tmp/ssh.go:35 +0x73

goroutine 2 [runnable]:

runtime.forcegchelper()

/usr/local/go/src/runtime/proc.go:90

runtime.goexit()

/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1

goroutine 3 [runnable]:

runtime.bgsweep()

/usr/local/go/src/runtime/mgc0.go:82

runtime.goexit()

/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1

goroutine 4 [runnable]:

runtime.runfinq()

/usr/local/go/src/runtime/malloc.go:712

runtime.goexit()

/usr/local/go/src/runtime/asm_amd64.s:2232 +0x1

exit status 2

错误应该是因为没有写端口:

start := tryConnect("root", "127.0.0.1:22")

在执行这个go程序之前,你应该已经试过在终端连一下看看可以了吧

ssh [email protected]

出错自己调错,可以在这里把err给print看一下

client, err = ssh.Dial("tcp", addr, config)

fmt.Println(err)

我用了一些从这个https://github.com/coreos/fleet/blob/master/ssh/ssh.go 改的ssh调用封装,推荐给你。

回答

以上是 【go】初学golang,想试试ssh,编译通过了,但是运行报错,大侠搭救下. T_T 的全部内容, 来源链接: www.h5w3.com/114968.html

回到顶部