Twiddle ssh auth, use password before --key-file flag before homedir before agent

This commit is contained in:
Pim van Pelt
2025-07-13 22:21:27 +02:00
parent 83797aaa34
commit 64212fce8c
2 changed files with 21 additions and 9 deletions

View File

@@ -84,6 +84,9 @@ func main() {
fmt.Printf("Using SSH key: %s\n", keyFile)
hasAuth++
}
} else {
fmt.Printf("Using specified SSH key: %s\n", keyFile)
hasAuth++
}
if password != "" {
fmt.Println("Using --password for authentication")

View File

@@ -103,11 +103,6 @@ func (rb *RouterBackup) Connect() error {
config.KeyExchanges = finalAlgorithms
}
// Note: Cipher overrides disabled - Go SSH library defaults work better
// if ciphers := ssh_config.Get(rb.hostname, "Ciphers"); ciphers != "" {
// config.Ciphers = ...
// }
if macs := ssh_config.Get(rb.hostname, "MACs"); macs != "" {
macList := strings.Split(macs, ",")
for i, mac := range macList {
@@ -126,15 +121,19 @@ func (rb *RouterBackup) Connect() error {
config.HostKeyAlgorithms = finalAlgorithms
}
// Try SSH agent first if available
// If explicit key file is provided, prioritize it over SSH agent
var keyFileAuth ssh.AuthMethod
var agentAuth ssh.AuthMethod
// Try SSH agent if available (but don't add to config.Auth yet)
if sshAuthSock := os.Getenv("SSH_AUTH_SOCK"); sshAuthSock != "" {
if conn, err := net.Dial("unix", sshAuthSock); err == nil {
agentClient := agent.NewClient(conn)
config.Auth = []ssh.AuthMethod{ssh.PublicKeysCallback(agentClient.Signers)}
agentAuth = ssh.PublicKeysCallback(agentClient.Signers)
}
}
// If SSH agent didn't work, try key file
// Try key file
if keyFile != "" {
// Expand ~ in keyFile path
if strings.HasPrefix(keyFile, "~/") {
@@ -150,11 +149,21 @@ func (rb *RouterBackup) Connect() error {
if err != nil {
fmt.Printf("%s: Unable to parse private key: %v\n", rb.hostname, err)
} else {
config.Auth = append(config.Auth, ssh.PublicKeys(signer))
keyFileAuth = ssh.PublicKeys(signer)
}
}
}
// Prioritize auth methods: explicit key file first, then SSH agent
if keyFileAuth != nil {
config.Auth = []ssh.AuthMethod{keyFileAuth}
if agentAuth != nil {
config.Auth = append(config.Auth, agentAuth)
}
} else if agentAuth != nil {
config.Auth = []ssh.AuthMethod{agentAuth}
}
// Fall back to password if available
if rb.password != "" {
config.Auth = append(config.Auth, ssh.Password(rb.password))