freifunkmanager/ssh/run.go

70 lines
1.5 KiB
Go
Raw Normal View History

2017-05-06 14:37:24 +02:00
package ssh
import (
"bytes"
"net"
2017-05-29 22:55:38 +02:00
"github.com/genofire/golang-lib/log"
2017-05-06 14:37:24 +02:00
"golang.org/x/crypto/ssh"
)
2017-07-08 18:42:03 +02:00
type SSHResultHandler func(string, string, error)
2017-05-06 14:37:24 +02:00
2017-07-07 08:12:25 +02:00
func SSHResultToString(result string) string {
if len(result) > 0 {
result = result[:len(result)-1]
}
2017-07-07 08:12:25 +02:00
return result
}
2017-07-07 08:12:25 +02:00
func SSHResultToStringHandler(handler SSHResultHandler) SSHResultHandler {
2017-07-08 18:42:03 +02:00
return func(addr string, result string, err error) {
handler(addr, SSHResultToString(result), err)
}
}
func (m *Manager) RunEverywhere(cmd string, handler SSHResultHandler) {
2017-07-08 19:00:36 +02:00
m.clientsMUX.Lock()
defer m.clientsMUX.Unlock()
2017-05-06 14:37:24 +02:00
for host, client := range m.clients {
2017-07-08 19:00:36 +02:00
go func() {
result, err := m.run(host, client, cmd)
handler(host, result, err)
}()
2017-05-06 14:37:24 +02:00
}
}
2017-07-07 08:12:25 +02:00
func (m *Manager) RunOn(addr net.TCPAddr, cmd string) (string, error) {
client, err := m.ConnectTo(addr)
if err != nil {
2017-07-07 08:12:25 +02:00
return "", err
}
return m.run(addr.IP.String(), client, cmd)
2017-05-06 14:37:24 +02:00
}
2017-07-07 08:12:25 +02:00
func (m *Manager) run(host string, client *ssh.Client, cmd string) (string, error) {
2017-05-06 14:37:24 +02:00
session, err := client.NewSession()
defer session.Close()
if err != nil {
log.Log.Warnf("can not create session on %s: %s", host, err)
2017-07-06 09:57:25 +02:00
m.clientsMUX.Lock()
2017-05-06 14:37:24 +02:00
delete(m.clients, host)
2017-07-06 09:57:25 +02:00
m.clientsMUX.Unlock()
2017-07-07 08:12:25 +02:00
return "", err
2017-05-06 14:37:24 +02:00
}
buffer := &bytes.Buffer{}
2017-07-07 08:12:25 +02:00
session.Stdout = buffer
2017-05-06 14:37:24 +02:00
if err != nil {
log.Log.Warnf("can not create pipe for run on %s: %s", host, err)
delete(m.clients, host)
2017-07-07 08:12:25 +02:00
return "", err
2017-05-06 14:37:24 +02:00
}
err = session.Run(cmd)
if err != nil {
2017-07-08 18:50:46 +02:00
log.Log.Debugf("could not run %s on %s: %s", cmd, host, err)
2017-07-07 08:12:25 +02:00
return "", err
2017-05-06 14:37:24 +02:00
}
2017-07-07 08:12:25 +02:00
return buffer.String(), nil
2017-05-06 14:37:24 +02:00
}