Ssh login go

From UVOO Tech Wiki
Revision as of 20:20, 19 December 2023 by Busk (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
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())
}