ssh.AuthMethod 里存放了 ssh 的认证方式。使用密码认证的话,就用 ssh.Password()来加载密码。使用密钥认证的话,就用 ssh.ParsePrivateKey() 或 ssh.ParsePrivateKeyWithPassphrase() 读取密钥,然后通过 ssh.PublicKeys() 加载进去。
ssh.config 这个 struct 存了 ssh 的配置参数,他有以下几个配置选项,以下引用自GoDoc 。
type Config struct {
// Rand provides the source of entropy for cryptographic
// primitives. If Rand is nil, the cryptographic random reader
// in package crypto/rand will be used.
// 加密时用的种子。默认就好
Rand io.Reader
// The maximum number of bytes sent or received after which a
// new key is negotiated. It must be at least 256. If
// unspecified, a size suitable for the chosen cipher is used.
// 密钥协商后的最大传输字节,默认就好
RekeyThreshold uint64
// The allowed key exchanges algorithms. If unspecified then a
// default set of algorithms is used.
//
KeyExchanges []string
// The allowed cipher algorithms. If unspecified then a sensible
// default is used.
// 连接所允许的加密算法
Ciphers []string
// The allowed MAC algorithms. If unspecified then a sensible default
// is used.
// 连接允许的 MAC (Message Authentication Code 消息摘要)算法,默认就好
MACs []string
}
基本上默认的就好啦。但是 Ciphers 需要修改下,默认配置下 Go 的 SSH 包提供的 Ciphers 包含以下加密方式
aes128-ctr aes192-ctr aes256-ctr aes128-gcm@openssh.com arcfour256 arcfour128
连 linux 通常没有问题,但是很多交换机其实默认只提供 aes128-cbc 3des-cbc aes192-cbc aes256-cbc 这些。因此我们还是加全一点比较好。
这里有两个地方要提一下
1、在 clientConfig 里有这么一段
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
这是因为默认密钥不受信任时,Go 的 ssh 包会在 HostKeyCallback 里把连接干掉(1.8 之后加的应该)。但是我们使用用户名密码连接的时候,这个太正常了不是么,所以让他 return nil 就好了。
2、在 NewSession() 后,我们定义了 modes 和 RequestPty。这是因为为之后使用 session.Shell() 模拟终端时,所建立的终端参数。如果不配的话,默认值可能导致在某些终端上执行失败。例如一些 H3C 的交换机,连接建立后默认推出来的 Copyright 可能会导致 ssh 连接异常,然后超时或者直接断掉。例如这样:
******************************************************************************
* Copyright (c) 2004-2016 Hangzhou H3C Tech. Co., Ltd. All rights reserved. *
* Without the owner's prior written consent, *
* no decompiling or reverse-engineering shall be allowed. *
******************************************************************************









