Home >Backend Development >Golang >How to SSH into Linux Servers Using Keys in Go?
Connecting to a server using SSH and a key in Golang can be achieved through the ssh package. Here's how you can do it:
The Dial function requires an ssh.AuthMethod instance, which can be created from SSH keys using ssh.PublicKeys. To obtain a signer from the PEM bytes, use ssh.ParsePrivateKey.
To use the Signers field of a private key, you can use ssh.PublicKeys(signers...) as your authentication method.
Example Code:
<code class="go">import ( "log" "net" "os" "github.com/gliderlabs/ssh" ) func main() { sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { log.Fatal(err) } agent := agent.NewClient(sock) signers, err := agent.Signers() if err != nil { log.Fatal(err) } auths := []ssh.AuthMethod{ssh.PublicKeys(signers...)} cfg := &ssh.ClientConfig{ User: "username", Auth: auths, } cfg.SetDefaults() client, err := ssh.Dial("tcp", "aws-hostname:22", cfg) if err != nil { log.Fatal(err) } session, err := client.NewSession() if err != nil { log.Fatal(err) } log.Println("we have a session!") }</code>
This code mimics the ssh -i x.pem user@host command, establishing an SSH session with the specified server using the provided key. You can now execute commands within the server through the session variable.
The above is the detailed content of How to SSH into Linux Servers Using Keys in Go?. For more information, please follow other related articles on the PHP Chinese website!