Difference between revisions of "Ssh login go"
Jump to navigation
Jump to search
(Created page with "``` package main import ( "bytes" "fmt" "log" "golang.org/x/crypto/ssh" ) func main() { config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ ss...") |
|||
Line 38: | Line 38: | ||
} | } | ||
fmt.Println(b.String()) | fmt.Println(b.String()) | ||
+ | } | ||
+ | ``` | ||
+ | |||
+ | |||
+ | ``` | ||
+ | package main | ||
+ | |||
+ | import ( | ||
+ | "fmt" | ||
+ | |||
+ | "golang.org/x/crypto/ssh" | ||
+ | "golang.org/x/crypto/ssh/knownhosts" | ||
+ | ) | ||
+ | |||
+ | func main() { | ||
+ | host := "<hostname>:<port>" | ||
+ | user := "<username>" | ||
+ | pwd := "<password>" | ||
+ | pKey := []byte("<privateKey>") | ||
+ | |||
+ | var err error | ||
+ | var signer ssh.Signer | ||
+ | |||
+ | signer, err = ssh.ParsePrivateKey(pKey) | ||
+ | if err != nil { | ||
+ | fmt.Println(err.Error()) | ||
+ | } | ||
+ | |||
+ | var hostkeyCallback ssh.HostKeyCallback | ||
+ | hostkeyCallback, err = knownhosts.New("~/.ssh/known_hosts") | ||
+ | if err != nil { | ||
+ | fmt.Println(err.Error()) | ||
+ | } | ||
+ | |||
+ | conf := &ssh.ClientConfig{ | ||
+ | User: user, | ||
+ | HostKeyCallback: hostkeyCallback, | ||
+ | Auth: []ssh.AuthMethod{ | ||
+ | ssh.Password(pwd), | ||
+ | ssh.PublicKeys(signer), | ||
+ | }, | ||
+ | } | ||
} | } | ||
``` | ``` |
Latest revision as of 20:26, 19 December 2023
package main import ( "bytes" "fmt" "log" "golang.org/x/crypto/ssh" ) func main() { config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ ssh.Password("password"), }, HostKeyCallback: ssh.InsecureIgnoreHostKey(), } client, err := ssh.Dial("tcp", "myserver:22", config) if err != nil { log.Fatal("Failed to dial: ", err) } // Each ClientConn can support multiple interactive sessions, // represented by a Session. session, err := client.NewSession() if err != nil { log.Fatal("Failed to create session: ", err) } defer session.Close() // Once a Session is created, you can execute a single command on // the remote side using the Run method. var b bytes.Buffer session.Stdout = &b if err := session.Run("/bin/hostname"); err != nil { log.Fatal("Failed to run: " + err.Error()) } fmt.Println(b.String()) }
package main import ( "fmt" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/knownhosts" ) func main() { host := "<hostname>:<port>" user := "<username>" pwd := "<password>" pKey := []byte("<privateKey>") var err error var signer ssh.Signer signer, err = ssh.ParsePrivateKey(pKey) if err != nil { fmt.Println(err.Error()) } var hostkeyCallback ssh.HostKeyCallback hostkeyCallback, err = knownhosts.New("~/.ssh/known_hosts") if err != nil { fmt.Println(err.Error()) } conf := &ssh.ClientConfig{ User: user, HostKeyCallback: hostkeyCallback, Auth: []ssh.AuthMethod{ ssh.Password(pwd), ssh.PublicKeys(signer), }, } }