support password flag.

Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
This commit is contained in:
Bo-Yi Wu 2016-12-27 16:23:52 +08:00
parent 4c85fe6ea9
commit d55423fa68
3 changed files with 37 additions and 18 deletions

View File

@ -24,7 +24,7 @@ Build the docker image with the following commands:
```
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -tags netgo
docker build --rm=true -t plugins/ssh .
docker build -t plugins/ssh .
```
Please note incorrectly building the image for the correct x64 linux and with

12
main.go
View File

@ -6,6 +6,7 @@ import (
"github.com/Sirupsen/logrus"
"github.com/joho/godotenv"
_ "github.com/joho/godotenv/autoload"
"github.com/urfave/cli"
)
@ -29,6 +30,11 @@ func main() {
EnvVar: "PLUGIN_USER,SSH_USER",
Value: "root",
},
cli.StringFlag{
Name: "password",
Usage: "user password",
EnvVar: "PLUGIN_PASSWORD,SSH_PASSWORD",
},
cli.StringSliceFlag{
Name: "host",
Usage: "connect to host",
@ -56,8 +62,9 @@ func main() {
EnvVar: "PLUGIN_SCRIPT,SSH_SCRIPT",
},
cli.StringFlag{
Name: "env-file",
Usage: "source env file",
Name: "env-file",
Usage: "source env file",
EnvVar: "ENV_FILE",
},
}
@ -75,6 +82,7 @@ func run(c *cli.Context) error {
Config: Config{
Key: c.String("ssh-key"),
User: c.String("user"),
Password: c.String("password"),
Host: c.StringSlice("host"),
Port: c.Int("port"),
Sleep: c.Int("sleep"),

View File

@ -13,13 +13,14 @@ import (
type (
Config struct {
Key string `json:"key"`
User string `json:"user"`
Host []string `json:"host"`
Port int `json:"port"`
Sleep int `json:"sleep"`
Timeout time.Duration `json:"timeout"`
Script []string `json:"script"`
Key string
User string
Password string
Host []string
Port int
Sleep int
Timeout time.Duration
Script []string
}
Plugin struct {
@ -28,8 +29,8 @@ type (
)
func (p Plugin) Exec() error {
if p.Config.Key == "" {
return fmt.Errorf("Error: Can't connect without a private SSH key.")
if p.Config.Key == "" && p.Config.Password == "" {
return fmt.Errorf("Error: Can't connect without a private SSH key or password.")
}
for i, host := range p.Config.Host {
@ -38,18 +39,28 @@ func (p Plugin) Exec() error {
strconv.Itoa(p.Config.Port),
)
signer, err := ssh.ParsePrivateKey([]byte(p.Config.Key))
// auths holds the detected ssh auth methods
auths := []ssh.AuthMethod{}
if err != nil {
return fmt.Errorf("Error: Failed to parse private key. %s", err)
if p.Config.Key != "" {
signer, err := ssh.ParsePrivateKey([]byte(p.Config.Key))
if err != nil {
return fmt.Errorf("Error: Failed to parse private key. %s", err)
}
auths = append(auths, ssh.PublicKeys(signer))
}
// figure out what auths are requested, what is supported
if p.Config.Password != "" {
auths = append(auths, ssh.Password(p.Config.Password))
}
config := &ssh.ClientConfig{
Timeout: p.Config.Timeout,
User: p.Config.User,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
Auth: auths,
}
fmt.Printf("+ ssh %s@%s -p %d\n", p.Config.User, addr, p.Config.Port)