【发布时间】:2018-03-22 01:11:15
【问题描述】:
我用 Go 写了一个 SSH 客户端,我想写一些测试。问题是我以前从未真正编写过正确的单元测试,而且大多数教程似乎都专注于为添加两个数字的函数或其他一些玩具问题编写测试。我读过关于模拟、使用接口和其他技术的文章,但我在应用它们时遇到了麻烦。此外,我的客户端将同时使用,以允许一次快速配置多个设备。不确定这是否会改变我编写测试的方式或添加额外的测试。任何帮助表示赞赏。
这是我的代码。基本上,Device 有 4 个主要功能:Connect、Send、Output/Err 和 Close 用于连接到设备,向其发送一组配置命令,捕获会话的输出,并分别关闭客户端。
package device
import (
"bufio"
"fmt"
"golang.org/x/crypto/ssh"
"io"
"net"
"time"
)
// A Device represents a remote network device.
type Device struct {
Host string // the device's hostname or IP address
client *ssh.Client // the client connection
session *ssh.Session // the connection to the remote shell
stdin io.WriteCloser // the remote shell's standard input
stdout io.Reader // the remote shell's standard output
stderr io.Reader // the remote shell's standard error
}
// Connect establishes an SSH connection to a device and sets up the session IO.
func (d *Device) Connect(user, password string) error {
// Create a client connection
client, err := ssh.Dial("tcp", net.JoinHostPort(d.Host, "22"), configureClient(user, password))
if err != nil {
return err
}
d.client = client
// Create a session
session, err := client.NewSession()
if err != nil {
return err
}
d.session = session
return nil
}
// configureClient sets up the client configuration for login
func configureClient(user, password string) *ssh.ClientConfig {
var sshConfig ssh.Config
sshConfig.SetDefaults()
sshConfig.Ciphers = append(sshConfig.Ciphers, "aes128-cbc", "aes256-cbc", "3des-cbc", "des-cbc", "aes192-cbc")
config := &ssh.ClientConfig{
Config: sshConfig,
User: user,
Auth: []ssh.AuthMethod{ssh.Password(password)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: time.Second * 5,
}
return config
}
// setupIO creates the pipes connected to the remote shell's standard input, output, and error
func (d *Device) setupIO() error {
// Setup standard input pipe
stdin, err := d.session.StdinPipe()
if err != nil {
return err
}
d.stdin = stdin
// Setup standard output pipe
stdout, err := d.session.StdoutPipe()
if err != nil {
return err
}
d.stdout = stdout
// Setup standard error pipe
stderr, err := d.session.StderrPipe()
if err != nil {
return err
}
d.stderr = stderr
return nil
}
// Send sends cmd(s) to the device's standard input. A device only accepts one call
// to Send, as it closes the session and its standard input pipe.
func (d *Device) Send(cmds ...string) error {
if d.session == nil {
return fmt.Errorf("device: session is closed")
}
defer d.session.Close()
// Start the shell
if err := d.startShell(); err != nil {
return err
}
// Send commands
for _, cmd := range cmds {
if _, err := d.stdin.Write([]byte(cmd + "\r")); err != nil {
return err
}
}
defer d.stdin.Close()
// Wait for the commands to exit
d.session.Wait()
return nil
}
// startShell requests a pseudo terminal (VT100) and starts the remote shell.
func (d *Device) startShell() error {
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.OCRNL: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
err := d.session.RequestPty("vt100", 0, 0, modes)
if err != nil {
return err
}
if err := d.session.Shell(); err != nil {
return err
}
return nil
}
// Output returns the remote device's standard output output.
func (d *Device) Output() ([]string, error) {
return readPipe(d.stdout)
}
// Err returns the remote device's standard error output.
func (d *Device) Err() ([]string, error) {
return readPipe(d.stdout)
}
// reapPipe reads an io.Reader line by line
func readPipe(r io.Reader) ([]string, error) {
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}
// Close closes the client connection.
func (d *Device) Close() error {
return d.client.Close()
}
// String returns the string representation of a `Device`.
func (d *Device) String() string {
return fmt.Sprintf("%s", d.Host)
}
【问题讨论】:
-
如果您想在公司网络中配置生产设备,我真的建议您,不要使用一些自己编写的程序来做到这一点。很可能会有错误,并且损坏可能很严重。请使用一些配置管理工具,例如ansible (ansible.com),配置您的设备。这些工具将通过 ssh 连接并进行配置。这些工具已准备好生产并已使用多年。
-
@mbuechmann:很好的建议,但与问题无关(就像整个序言与问题无关)
-
@mbuechmann 感谢您的建议。出于好奇,像 Ansible 这样的东西和我的程序有什么区别(一旦我的程序经过全面测试并被证明是稳定的)?除了 Flimzy 所说的,我仍然想学习如何使我的程序尽可能健壮,并继续开发我的程序供个人使用/练习。
-
您需要花费很多人年的开发时间才能获得与现有解决方案同等的功能。不是您想在个人项目中尝试的东西。如果你的公司真的想把钱花在这上面,我想你可以做到,但作为一个真正的管理员,如果没有几年的发展,我可能不希望这个靠近我的生产环境......
标签: unit-testing testing go ssh network-programming