代码框架为:
func NewSSHClient(ip string, port int, user, passwd string) (*SSHClient, error) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(passwd),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 30 * time.Second,
}
sshConn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", ip, port), config)
if err != nil {
return nil, err
}
sftpClient, err := sftp.NewClient(sshConn)
if err != nil {
return nil, err
}
return &SSHClient{
Ip: ip,
port: port,
user: user,
passwd: passwd,
ssh: sshConn,
sftp: sftpClient,
}, nil
}
func main() {
// errors := make(chan error)
limits := make(chan struct{}, 256)
var wg sync.WaitGroup
for host := range hosts {
wg.Add(1)
go func(host string) {
defer wg.Done()
defer func(limits *chan struct{}) { <-*limits }(&limits)
limits <- struct{}{}
for {
for _, ng := range nginxHost {
a, err := NewSSHClient(hosts[host], host)
if err != nil {
log.Errorf("%s NewMonitor fail err:%s", host, err)
time.Sleep(30 * time.Second)
continue
}
a.dosomething()
}
time.Sleep(30 * time.Second)
}
}(host)
}
wg.Wait()
}
出错还是比较有规律,比如某个服务器前面三次连接正常,第四次开始及以后都会一直报错No connection could be made because the target machine actively refused it.
看看这篇文章:https://dailydevsblog.com/troubleshoot/resolved-no-connection...