Created
November 9, 2022 05:35
-
-
Save Shackelford-Arden/04f8e08bdf683050137205d50561df5a to your computer and use it in GitHub Desktop.
Just a small script to connect to a host via SSH in Go :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"golang.org/x/crypto/ssh" | |
"github.com/kelseyhightower/envconfig" | |
) | |
type ConnectionOpts struct { | |
PrivateKeyPath string `envconfig:"PRIVATE_KEY_PATH" default:""` | |
RemoteHost string `envconfig:"REMOTE_HOST" required:"true"` | |
RemoteUser string `envconfig:"REMOTE_USER" required:"true"` | |
RemoteUserPass string `envconfig:"REMOTE_USER_PASS"` | |
} | |
func CreatePrivKeyAuth(privKeyPath string, user string) (ssh.ClientConfig, error) { | |
// A public key may be used to authenticate against the remote | |
// server by using an unencrypted PEM-encoded private key file. | |
// | |
// If you have an encrypted private key, the crypto/x509 package | |
// can be used to decrypt it. | |
key, err := os.ReadFile(privKeyPath) | |
if err != nil { | |
log.Fatalf("unable to read private key: %v", err) | |
} | |
// Create the Signer for this private key. | |
signer, err := ssh.ParsePrivateKey(key) | |
if err != nil { | |
log.Fatalf("unable to parse private key: %v", err) | |
} | |
config := &ssh.ClientConfig{ | |
User: user, | |
Auth: []ssh.AuthMethod{ | |
ssh.PublicKeys(signer), | |
}, | |
HostKeyCallback: ssh.InsecureIgnoreHostKey(), | |
} | |
return *config, nil | |
} | |
func main() { | |
var conOpts ConnectionOpts | |
err := envconfig.Process("", &conOpts) | |
if err != nil { | |
log.Fatalf(err.Error()) | |
} | |
var config ssh.ClientConfig | |
if conOpts.PrivateKeyPath != "" { | |
config, err = CreatePrivKeyAuth(conOpts.PrivateKeyPath, conOpts.RemoteUser) | |
} else { | |
config = ssh.ClientConfig{ | |
User: conOpts.RemoteUser, | |
Auth: []ssh.AuthMethod{ | |
ssh.Password(conOpts.RemoteUserPass), | |
}, | |
HostKeyCallback: ssh.InsecureIgnoreHostKey(), | |
} | |
} | |
var remoteHost = fmt.Sprintf("%s:%s", conOpts.RemoteHost, "22") | |
// Connect to the remote server and perform the SSH handshake. | |
client, err := ssh.Dial("tcp", remoteHost, &config) | |
if err != nil { | |
log.Fatalf("unable to connect: %v", err) | |
} | |
defer client.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment