panssh
A Golang helper library to get connection to an SSH server.
You can connect using:
- a password
- keys passed as strings
- key files
- an ssh-agent (including Pageant)
- any combination of the above
It calls the standard ssh.*
library and xanzy/ssh-agent for ssh-agent, and returns standard *ssh.Client
.
Usage:
A complex example
func doSomething() {
var p properties.Properties
// load properties
host := p.GetString("ssh.host", "")
port := p.GetInt("ssh.port", 22)
user := p.GetString("ssh.user", "")
pwd := p.GetString("ssh.pwd", "")
agent := p.GetBool("ssh.agent", false)
key := p.GetString("ssh.key", "")
keyPwd := p.GetString("ssh.key.pwd", "")
keyFile := p.GetString("ssh.key.file", "")
conn, e := panssh.Connect(&panssh.Config{
Host: host, Port: port, User: user,
Pwd: pwd, UsePwd: pwd != "", UseAgent: agent,
Keys: []panssh.K{{key, keyPwd}}, UseKeys: key != "",
KeyFiles: []panssh.K{{keyFile, keyPwd}}, UseKeyFiles: keyFile != "",
})
if e != nil {
fmt.Printf("Failed to dial ssh: " + e.Error())
return
}
defer conn.Close()
// work over ssh
}
Connecting with password
conn, e := panssh.Connect(&panssh.Config{
Host: "example.com",
Port: 22,
User: "root",
Pwd: pwd,
UsePwd: true
})
Connecting with a key
key := `-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----`
conn, e := panssh.Connect(&panssh.Config{
Host: "example.com",
Port: 22,
User: "root",
Keys: []panssh.K{{K: key}},
UseKeys: true
})
Connecting with an encrypted key
key := `-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----`
conn, e := panssh.Connect(&panssh.Config{
Host: "example.com",
Port: 22,
User: "root",
Keys: []panssh.K{{key, "password"}},
UseKeys: true
})
Connecting with an encrypted key file
conn, e := panssh.Connect(&panssh.Config{
Host: "example.com",
Port: 22,
User: "root",
KeyFiles: []panssh.K{{"/tmp/private.key", "password"}},
UseKeyFiles: true
})
Connecting with password (if specified) and agent
conn, e := panssh.Connect(&panssh.Config{
Host: "example.com",
Port: 22,
User: "root",
Pwd: pwd,
UsePwd: pwd != "",
UseAgent: true
})
Config structure:
type K struct {
// a key file or a key data
K string
// a password for the key (if needed)
P string
}
type Config struct {
// server host
Host string
// server port
Port int
// user name
User string
// password
Pwd string
// keys
Keys []K
// key files
KeyFiles []K
// ssh.HostKeyCallback function
// if it's nil, ssh.InsecureIgnoreHostKey() is used
HostKeyCallback ssh.HostKeyCallback
// should we use password
UsePwd bool
// should we use keys
UseKeys bool
// should we use key files
UseKeyFiles bool
// should we use ssh-agent
UseAgent bool
// should we ignore any errors related to ssh-agent, reading key
// files, or key parsing or decryption
IgnoreKeyErrors bool
}