Skip to content

Commit b101c18

Browse files
committed
initial commit for a parallel ssh command helper
0 parents  commit b101c18

File tree

10 files changed

+430
-0
lines changed

10 files changed

+430
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.idea/

README.md

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Light-weight parallel remote ssh tool
2+
LLSH is for running shell commands on remote machines through SSH, it's quite common that sometimes
3+
operators need to run some commands on multiple servers.
4+
5+
LLSH is a super simple and direct tool with only command line arguments, no need to use conf file.
6+
You can simply run the SSH commands through two different ways:
7+
* create a process running `/bin/ssh` command to run the remote commands
8+
* use SSH protocol to access remote servers
9+
10+
The first approach works fine when all of the settings are already ready in local SSH, but it has
11+
extra costs to create a process, the second one means faster and less resource and supports password
12+
and public key to authenticate.
13+
14+
## Usages
15+
```bash
16+
// Use ssh command to access host1 and host2 running ls.
17+
$ llsh --hosts hosts1,hosts2 \
18+
--user sojiang \
19+
-c "ls"
20+
```
21+
22+
### Help
23+
```bash
24+
$ llsh --help
25+
llsh executes the remote shell command on multiple remote servers
26+
27+
Usage:
28+
llsh [flags]
29+
30+
Flags:
31+
-c, --command string The command you need to run on the servers
32+
-h, --help help for llsh
33+
--hosts string The host names for remote server, split by comma, for example, host1,host2,host3
34+
-p, --password If we need to input password from terminal
35+
-k, --publickey string The file path of the public key, like ~/.ssh/id_rsa.pub
36+
--ssh_command_path string The file path of the ssh command, like /bin/ssh (default "ssh")
37+
--use_ssh_command Use the ssh executable, like /bin/ssh (default true)
38+
-u, --user string The username for login user
39+
```

cmd/llsh/llsh.go

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package main
2+
3+
import (
4+
"github.com/songrgg/llsh/pkg/helper"
5+
"github.com/songrgg/llsh/pkg/llsh/cmd"
6+
)
7+
8+
func main() {
9+
rootCmd := cmd.NewLLSHCommand()
10+
if err := rootCmd.Execute(); err != nil {
11+
helper.Errorlq(err)
12+
}
13+
}

go.mod

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
module github.com/songrgg/llsh
2+
3+
go 1.12
4+
5+
require (
6+
github.com/fatih/color v1.7.0
7+
github.com/mattn/go-colorable v0.1.2 // indirect
8+
github.com/spf13/cobra v0.0.5
9+
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9
10+
)

go.sum

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
2+
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
3+
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
4+
github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
5+
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
6+
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
7+
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
8+
github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys=
9+
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
10+
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
11+
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
12+
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
13+
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
14+
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
15+
github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
16+
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
17+
github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE=
18+
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
19+
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
20+
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
21+
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
22+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
23+
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
24+
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
25+
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
26+
github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s=
27+
github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU=
28+
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
29+
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
30+
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
31+
github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
32+
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
33+
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
34+
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
35+
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0=
36+
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
37+
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a h1:1n5lsVfiQW3yfsRGu98756EH1YthsFqr/5mxHduZW2A=
38+
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
39+
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8=
40+
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
41+
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
42+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
43+
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

pkg/helper/error.go

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package helper
2+
3+
import (
4+
"fmt"
5+
"os"
6+
)
7+
8+
// Errorfq prints the message with format and exits with 1.
9+
func Errorfq(format string, a ...interface{}) {
10+
fmt.Printf(format, a)
11+
os.Exit(1)
12+
}
13+
14+
// Errorlq prints the message with new line and exits with 1.
15+
func Errorlq(a ...interface{}) {
16+
fmt.Println(a)
17+
os.Exit(1)
18+
}

pkg/helper/password.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package helper
2+
3+
import (
4+
"fmt"
5+
"os"
6+
7+
"golang.org/x/crypto/ssh/terminal"
8+
)
9+
10+
func ReadPassword(prompt string) (string, error) {
11+
fmt.Fprintf(os.Stderr, prompt)
12+
13+
tty, err := os.Open("/dev/tty")
14+
if err != nil {
15+
return "", fmt.Errorf(`TTY is required for reading password, but /dev/tty can't be opened: %v`, err)
16+
}
17+
18+
password, err := terminal.ReadPassword(int(tty.Fd()))
19+
if err != nil {
20+
return "", fmt.Errorf(`can't read password: %v`, err)
21+
}
22+
23+
if prompt != "" {
24+
fmt.Fprintln(os.Stderr)
25+
}
26+
27+
return string(password), nil
28+
}

pkg/llsh/cmd/cmd.go

+148
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
package cmd
2+
3+
import (
4+
"fmt"
5+
"io/ioutil"
6+
"strings"
7+
"sync"
8+
9+
"github.com/fatih/color"
10+
"github.com/songrgg/llsh/pkg/helper"
11+
"github.com/songrgg/llsh/pkg/ssh"
12+
"github.com/spf13/cobra"
13+
)
14+
15+
type options struct {
16+
Command string
17+
Hosts string
18+
User string
19+
UseSSHCommand bool
20+
UsePassword bool
21+
PublicKeyPath string
22+
SSHCommandPath string
23+
}
24+
25+
type sshResult struct {
26+
Host string
27+
Result string
28+
Error error
29+
}
30+
31+
// NewLLSHCommand creates `llsh` command.
32+
func NewLLSHCommand() *cobra.Command {
33+
options := options{}
34+
35+
cmds := &cobra.Command{
36+
Use: "llsh",
37+
Short: "llsh executes the remote shell command on multiple remote servers",
38+
Run: func(cmd *cobra.Command, args []string) {
39+
options.validate()
40+
options.run()
41+
},
42+
}
43+
44+
cmds.PersistentFlags().StringVar(&options.Hosts, "hosts", "",
45+
"The host names for remote server, split by comma, for example, host1,host2,host3")
46+
cmds.PersistentFlags().StringVarP(&options.User, "user", "u", "",
47+
"The username for login user")
48+
cmds.PersistentFlags().StringVarP(&options.Command, "command", "c", "",
49+
"The command you need to run on the servers")
50+
cmds.PersistentFlags().BoolVar(&options.UseSSHCommand, "use_ssh_command", true,
51+
"Use the ssh executable, like /bin/ssh")
52+
cmds.PersistentFlags().BoolVarP(&options.UsePassword, "password", "p", false,
53+
"If we need to input password from terminal")
54+
cmds.PersistentFlags().StringVarP(&options.PublicKeyPath, "publickey", "k", "",
55+
"The file path of the public key, like ~/.ssh/id_rsa.pub")
56+
cmds.PersistentFlags().StringVar(&options.SSHCommandPath, "ssh_command_path", "ssh",
57+
"The file path of the ssh command, like /bin/ssh")
58+
return cmds
59+
}
60+
61+
func (o *options) authMethods() []ssh.AuthMethod {
62+
authMethods := make([]ssh.AuthMethod, 0)
63+
if o.UsePassword && !o.UseSSHCommand {
64+
password, err := helper.ReadPassword("Password: ")
65+
if err != nil {
66+
helper.Errorlq("password can't be read")
67+
}
68+
69+
authMethods = append(authMethods, ssh.AuthMethod{
70+
Type: ssh.AuthByPassword,
71+
Content: password,
72+
})
73+
}
74+
75+
if o.PublicKeyPath != "" && !o.UseSSHCommand {
76+
content, err := ioutil.ReadFile(o.PublicKeyPath)
77+
if err != nil {
78+
helper.Errorlq("couldn't read the content of public key: ", err)
79+
}
80+
81+
authMethods = append(authMethods, ssh.AuthMethod{
82+
Type: ssh.AuthByPublicKey,
83+
Content: string(content),
84+
})
85+
}
86+
return authMethods
87+
}
88+
89+
func (o *options) run() {
90+
authMethods := o.authMethods()
91+
92+
hosts := strings.Split(o.Hosts, ",")
93+
var wg sync.WaitGroup
94+
var results []sshResult
95+
var lock = sync.Mutex{}
96+
for _, host := range hosts {
97+
wg.Add(1)
98+
go func(host string) {
99+
t := &ssh.Task{
100+
Username: o.User,
101+
AuthMethods: authMethods,
102+
Host: host,
103+
Script: o.Command,
104+
UseSSHCommand: o.UseSSHCommand,
105+
SSHCommandPath: o.SSHCommandPath,
106+
}
107+
108+
result, err := t.Execute()
109+
if err != nil {
110+
result = fmt.Sprintf("fail to execute task: %s", result)
111+
}
112+
113+
lock.Lock()
114+
results = append(results, sshResult{
115+
Host: host,
116+
Result: result,
117+
Error: err,
118+
})
119+
lock.Unlock()
120+
wg.Done()
121+
}(host)
122+
}
123+
wg.Wait()
124+
125+
for _, result := range results {
126+
if result.Error != nil {
127+
color.Red("Host %s\n", result.Host)
128+
} else {
129+
color.Green("Host %s\n", result.Host)
130+
}
131+
132+
_, _ = fmt.Println(result.Result)
133+
}
134+
}
135+
136+
func (o *options) validate() {
137+
if o.Hosts == "" {
138+
helper.Errorlq("hosts can't be empty")
139+
}
140+
141+
if o.PublicKeyPath != "" && o.UsePassword {
142+
helper.Errorlq("can't use both public key and password")
143+
}
144+
145+
if (o.PublicKeyPath != "" || o.UsePassword) && o.UseSSHCommand {
146+
color.Yellow("Public key or password option will be ignored when using ssh command")
147+
}
148+
}

0 commit comments

Comments
 (0)