freifunkmanager/ssh/run.go

56 lines
1.2 KiB
Go
Raw Permalink Normal View History

2017-05-06 14:37:24 +02:00
package ssh
import (
"bytes"
"net"
2019-06-10 02:57:36 +02:00
"github.com/bdlm/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)
}
}
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
}
2018-06-30 01:45:51 +02:00
defer client.Close()
return Run(addr.IP.String(), client, cmd)
2017-05-06 14:37:24 +02:00
}
func 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 {
2018-06-30 01:45:51 +02:00
log.Warnf("can not create session on %s: %s", host, err)
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 {
2018-06-30 01:45:51 +02:00
log.Warnf("can not create pipe for run on %s: %s", host, err)
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 {
2018-06-30 01:45:51 +02:00
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
}