func (c *SftpClient) Connect() error { auth := []ssh.AuthMethod{} if c.authMethod == "key" { key, _ := c.GetKey(c.keyPath) auth = []ssh.AuthMethod{ ssh.PublicKeys(key), } } else if c.authMethod == "password" { auth = []ssh.AuthMethod{ ssh.Password(c.password), } } config := &ssh.ClientConfig{ User: c.username, Auth: auth, } sHost := strings.Join([]string{c.hostname, strconv.FormatInt(c.port, 10)}, ":") sshClient, err := ssh.Dial("tcp", sHost, config) if err != nil { return err } sftpClient, err := sftp.NewClient(sshClient) if err == nil { c.Client = sftpClient } return err }
func main() { if len(os.Args) < 2 { usage() return } username, hostnames, pass := parse() config := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.Password(string(pass)), }, } hosts := []*Host{} for _, host := range hostnames { client, err := ssh.Dial("tcp", host+":22", config) if err != nil { log.Fatal("Failed to dial: ", err) } hosts = append(hosts, &Host{host, client}) } lock := make(chan string) for { fmt.Print("$ ") reader := bufio.NewReader(os.Stdin) input, err := reader.ReadString('\n') if err != nil { log.Fatal("Error getting user input: ", err) } for _, host := range hosts { go func(host *Host) { // Each ClientConn can support multiple interactive sessions, // represented by a Session. session, err := host.client.NewSession() if err != nil { log.Fatal("Failed to create session: ", err) } // Once a Session is created, you can execute a single command on // the remote side using the Run method. var b bytes.Buffer session.Stdout = &b if err := session.Run(input); err != nil { lock <- fmt.Sprintf("%v\n%v", host.hostname, err) } else { lock <- fmt.Sprintf("%v\n%v", host.hostname, b.String()) } }(host) } for _ = range hosts { fmt.Println(<-lock) } } }
func TestNew_Invalid(t *testing.T) { clientConfig := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password("i-am-invalid"), }, } address := newMockLineServer(t) conn := func() (net.Conn, error) { conn, err := net.Dial("tcp", address) if err != nil { t.Errorf("Unable to accept incoming connection: %v", err) } return conn, err } config := &Config{ Connection: conn, SSHConfig: clientConfig, } _, err := New(address, config) if err == nil { t.Fatal("should have had an error connecting") } }
func TestStart(t *testing.T) { clientConfig := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password("pass"), }, } address := newMockLineServer(t) conn := func() (net.Conn, error) { conn, err := net.Dial("tcp", address) if err != nil { t.Fatalf("unable to dial to remote side: %s", err) } return conn, err } config := &Config{ Connection: conn, SSHConfig: clientConfig, } client, err := New(address, config) if err != nil { t.Fatalf("error connecting to SSH: %s", err) } var cmd packer.RemoteCmd stdout := new(bytes.Buffer) cmd.Command = "echo foo" cmd.Stdout = stdout client.Start(&cmd) }
// PrepareConfig is used to turn the *SSHConfig provided into a // usable *Config for client initialization. func PrepareConfig(conf *SSHConfig) (*Config, error) { sshConf := &ssh.ClientConfig{ User: conf.User, } if conf.KeyFile != "" { key, err := ioutil.ReadFile(conf.KeyFile) if err != nil { return nil, fmt.Errorf("Failed to read key file '%s': %v", conf.KeyFile, err) } signer, err := ssh.ParsePrivateKey(key) if err != nil { return nil, fmt.Errorf("Failed to parse key file '%s': %v", conf.KeyFile, err) } sshConf.Auth = append(sshConf.Auth, ssh.PublicKeys(signer)) } if conf.Password != "" { sshConf.Auth = append(sshConf.Auth, ssh.Password(conf.Password)) sshConf.Auth = append(sshConf.Auth, ssh.KeyboardInteractive(PasswordKeyboardInteractive(conf.Password))) } host := fmt.Sprintf("%s:%d", conf.Host, conf.Port) config := &Config{ SSHConfig: sshConf, Connection: ConnectFunc("tcp", host), } return config, nil }
func (d *ESX5Driver) connect() error { address := fmt.Sprintf("%s:%d", d.Host, d.Port) auth := []gossh.AuthMethod{ gossh.Password(d.Password), gossh.KeyboardInteractive( ssh.PasswordKeyboardInteractive(d.Password)), } // TODO(dougm) KeyPath support sshConfig := &ssh.Config{ Connection: ssh.ConnectFunc("tcp", address), SSHConfig: &gossh.ClientConfig{ User: d.Username, Auth: auth, }, NoPty: true, } comm, err := ssh.New(address, sshConfig) if err != nil { return err } d.comm = comm return nil }
// connect is a private function to set up the ssh connection. It is called at the beginning of every public // function. func (config *Config) connect() (*ssh.Session, error) { sshconfig := &ssh.ClientConfig{ User: config.User, } if config.User == "" { u, err := user.Current() if err != nil { return nil, err } sshconfig.User = u.Username } if config.Password != "" { sshconfig.Auth = append(sshconfig.Auth, ssh.Password(config.Password)) } // By default, we try to include ~/.ssh/id_rsa. It is not an error if this file // doesn't exist. keyfile := os.Getenv("HOME") + "/.ssh/id_rsa" pkey, err := parsekey(keyfile) if err == nil { sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey)) } // Include any additional key files for _, keyfile = range config.KeyFiles { pkey, err = parsekey(keyfile) if err != nil { if config.AbortOnError == true { log.Fatalf("%s", err) } return nil, err } sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey)) } host := config.Host if strings.Contains(host, ":") == false { host = host + ":22" } client, err := ssh.Dial("tcp", host, sshconfig) if err != nil { if config.AbortOnError == true { log.Fatalf("%s", err) } return nil, err } session, err := client.NewSession() if err != nil { if config.AbortOnError == true { log.Fatalf("%s", err) } return nil, err } return session, err }
// SSHConfigPassword is a convience function that takes a username and password // and returns a new ssh.ClientConfig setup to pass that username and password. func SSHConfigPassword(user string, pass string) *ssh.ClientConfig { return &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ ssh.Password(pass), }, } }
func (s *Command) getSSHAuthMethods() []ssh.AuthMethod { var methods []ssh.AuthMethod if s.Password != nil { methods = append(methods, ssh.Password(*s.Password)) } return methods }
/* Make an attempt from the template. The attempt will eventually go back on d to the hostmaster, and will be executed against h. */ func (t Template) Attempt(d chan *Attempt, h string) *Attempt { a := &Attempt{DoneChan: d, Host: h, Pass: t.Pass} a.Config = &ssh.ClientConfig{User: t.User, ClientVersion: *gc.Sshvs, Auth: []ssh.AuthMethod{ ssh.Password(t.Pass), }, } return a }
func sshConfig(state multistep.StateBag) (*ssh.ClientConfig, error) { config := state.Get("config").(config) clientConfig := ssh.ClientConfig{User: config.SSHUsername} if config.OsSnapshot == "" && config.IpxeUrl == "" { // default case where vultr generated the password password := state.Get("default_password").(string) clientConfig.Auth = []ssh.AuthMethod{ssh.Password(password)} } else if config.SSHPassword != "" { // special case but we got a password clientConfig.Auth = []ssh.AuthMethod{ssh.Password(config.SSHPassword)} } else { // special case and we got a key signer, err := ssh.ParsePrivateKey([]byte(config.SSHPrivateKey)) if err != nil { return nil, fmt.Errorf("Error setting up SSH config: %s", err) } clientConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)} } return &clientConfig, nil }
/* New makes a new attempt from a template with Pass and Config filled in, and a version string of v. */ func (t template) New(p, v string) attempt { n := attempt{User: t.User, Pass: p, Host: t.Host, Err: nil} n.Config = &ssh.ClientConfig{ User: n.User, Auth: []ssh.AuthMethod{ ssh.Password(n.Pass), }, ClientVersion: v, } return n }
func ExecuteHostSSHCmd(state multistep.StateBag, cmd string) (stdout string, err error) { config := state.Get("commonconfig").(CommonConfig) // Setup connection config sshConfig := &gossh.ClientConfig{ User: config.Username, Auth: []gossh.AuthMethod{ gossh.Password(config.Password), }, } return doExecuteSSHCmd(cmd, config.HostIp+":22", sshConfig) }
func NewRemotePassAuthRunner(user, host, password string) (*Remote, error) { config := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.Password(password)}, } server, err := ssh.Dial("tcp", host, config) if err != nil { return nil, err } return &Remote{server}, nil }
func (self *Script) Execute(host *Host, out io.Writer) error { usr, err := user.Current() if err != nil { return err } if host.User == "" { host.User = usr.Username } cfg := &ssh.ClientConfig{ User: host.User, } if host.Password != "" { cfg.Auth = []ssh.AuthMethod{ ssh.Password(host.Password), } } else { content, err := ioutil.ReadFile(usr.HomeDir + "/.ssh/id_rsa") if err != nil { content, err = ioutil.ReadFile(usr.HomeDir + "/.ssh/id_dsa") if err != nil { return err } } key, err := ssh.ParsePrivateKey(content) if err != nil { return err } cfg.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)} } client, err := ssh.Dial("tcp", host.Name+":"+strconv.Itoa(host.Port), cfg) if err != nil { fmt.Fprintln(out, err.Error()) return err } session, err := client.NewSession() if err != nil { fmt.Fprintln(out, err.Error()) return err } defer session.Close() session.Stdout = out session.Stderr = out if !self.HideBoundaries { fmt.Fprintln(out, "---------------------- script started ----------------------") } if err := session.Run(self.Content); err != nil { return err } if !self.HideBoundaries { fmt.Fprintln(out, "---------------------- script finished ----------------------") } return nil }
func DialWithPassword(addr string, username string, password string) (client *ssh.Client, err error) { clientConfig := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.Password(password), }, } client, err = ssh.Dial("tcp", addr, clientConfig) if err != nil { return nil, fmt.Errorf("[DialWithPassword] Failed to dial: %s", err.Error()) } return }
func main() { // signer, err := ssh.ParsePrivateKey([]byte(pemBytes)) // if err != nil { // panic(err) // } // clientKey := &keychain{signer} password := "******" authMethods := []ssh.AuthMethod{} keyboardInteractiveChallenge := func( user, instruction string, questions []string, echos []bool, ) (answers []string, err error) { if len(questions) == 0 { return []string{}, nil } return []string{password}, nil } authMethods = append(authMethods, ssh.KeyboardInteractive(keyboardInteractiveChallenge)) authMethods = append(authMethods, ssh.Password(password)) config := &ssh.ClientConfig{ User: "******", Auth: authMethods, } c, err := ssh.Dial("tcp", "127.0.0.1:22", config) if err != nil { log.Println("unable to dial remote side:", err) } defer c.Close() // Create a session session, err := c.NewSession() if err != nil { log.Fatalf("unable to create session: %s", err) } defer session.Close() b, err := session.Output("ls /data/ -l") if err != nil { log.Fatalf("failed to execute: %s", err) } log.Println("Output: ", string(b)) return }
//returns a new deployment func newDeploy() (d *deploy, err error) { cfg := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ ssh.Password(pass), }, } fmt.Println("SSH-ing into " + hostname) cl, err := ssh.Dial("tcp", hostname+":22", cfg) d = &deploy{cl: cl} return }
// PrepareConfig is used to turn the *SSHConfig provided into a // usable *Config for client initialization. func PrepareConfig(conf *SSHConfig) (*Config, error) { sshConf := &ssh.ClientConfig{ User: conf.User, } if conf.KeyFile != "" { fullPath, err := homedir.Expand(conf.KeyFile) if err != nil { return nil, fmt.Errorf("Failed to expand home directory: %v", err) } key, err := ioutil.ReadFile(fullPath) if err != nil { return nil, fmt.Errorf("Failed to read key file '%s': %v", conf.KeyFile, err) } // We parse the private key on our own first so that we can // show a nicer error if the private key has a password. block, _ := pem.Decode(key) if block == nil { return nil, fmt.Errorf( "Failed to read key '%s': no key found", conf.KeyFile) } if block.Headers["Proc-Type"] == "4,ENCRYPTED" { return nil, fmt.Errorf( "Failed to read key '%s': password protected keys are\n"+ "not supported. Please decrypt the key prior to use.", conf.KeyFile) } signer, err := ssh.ParsePrivateKey(key) if err != nil { return nil, fmt.Errorf("Failed to parse key file '%s': %v", conf.KeyFile, err) } sshConf.Auth = append(sshConf.Auth, ssh.PublicKeys(signer)) } if conf.Password != "" { sshConf.Auth = append(sshConf.Auth, ssh.Password(conf.Password)) sshConf.Auth = append(sshConf.Auth, ssh.KeyboardInteractive(PasswordKeyboardInteractive(conf.Password))) } host := fmt.Sprintf("%s:%d", conf.Host, conf.Port) config := &Config{ SSHConfig: sshConf, Connection: ConnectFunc("tcp", host), } return config, nil }
func (s *Command) getSSHAuthMethods() ([]ssh.AuthMethod, error) { var methods []ssh.AuthMethod if s.Password != nil { methods = append(methods, ssh.Password(*s.Password)) } if s.IdentityFile != nil { key, err := s.getSSHKey(*s.IdentityFile) if err != nil { return nil, err } methods = append(methods, ssh.PublicKeys(key)) } return methods, nil }
func (c *sshClientImpl) ExecCommand(username string, password string, ip string, command string) (string, error) { config := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.Password(password), }, } client, err := ssh.Dial("tcp", ip+":22", config) session, err := client.NewSession() if err != nil { return "", err } defer session.Close() output, err := session.Output(command) return string(output), err }
func (c *Client) Connect() (e error) { if c.Port == 0 { c.Port = 22 } var auths []ssh.AuthMethod if c.password != "" { auths = append(auths, ssh.Password(c.password)) } else if c.Agent, e = net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); e == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(c.Agent).Signers)) } config := &ssh.ClientConfig{ User: c.User, Auth: auths, } c.Conn, e = ssh.Dial("tcp", fmt.Sprintf("%s:%d", c.Host, c.Port), config) return e }
func (c *Config) Connection() (*ssh.Client, error) { port := c.Port if port == 0 { port = 22 } var auths []ssh.AuthMethod if c.Password != "" { auths = append(auths, ssh.Password(c.Password)) } else if sshAgent, e := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); e == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)) } config := &ssh.ClientConfig{ User: c.User, Auth: auths, } return ssh.Dial("tcp", fmt.Sprintf("%s:%d", c.Host, port), config) }
func (ai *AccountInfo) ClientConfig() (config *ssh.ClientConfig, err error) { config = &ssh.ClientConfig{ User: ai.Account, HostKeyCallback: CheckHostKey(ai.HostKey), } if ai.Key != "" { private, err := ssh.ParsePrivateKey([]byte(ai.Key)) if err != nil { log.Error("failed to parse keyfile: %s", err.Error()) return nil, err } config.Auth = append(config.Auth, ssh.PublicKeys(private)) } if ai.Password != "" { config.Auth = append(config.Auth, ssh.Password(ai.Password)) } return }
//初始化ssh func initSSH() { var ( user = iniFile.Section("ssh").Key("user").String() pwd = iniFile.Section("ssh").Key("pwd").String() host = iniFile.Section("ssh").Key("host").String() ) if user == "" || pwd == "" || host == "" { log.Fatalln("读取ssh信息出错") } config := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ ssh.Password(pwd), }, } sshClient, err = ssh.Dial("tcp", fmt.Sprintf("%s:%s", host, "22"), config) if err != nil { log.Fatalln("连接主机出错,错误信息为:" + err.Error()) } }
func main() { defer log.Flush() sshPassword = "******" sshUser = "******" sshServerIP = "10.49.116.2:22" sshServerPort = "22" config := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password("R0yJ3nk1n5"), }, } client, err := ssh.Dial("tcp", "10.49.116.2:22", config) if err != nil { panic("Failed to dial: " + err.Error()) } log.Info("Connection (SSH) to " + sshServerIP + ":" + sshServerPort) session, err := client.NewSession() if err != nil { panic("Failed to create session: " + err.Error()) } defer session.Close() log.Info("Connected") var b bytes.Buffer session.Stdout = &b if err := session.Run("/usr/bin/whoami"); err != nil { panic("Failed to run: " + err.Error()) } fmt.Println(b.String()) }
func SSHConfig(state multistep.StateBag) (*gossh.ClientConfig, error) { config := state.Get("commonconfig").(CommonConfig) auth := []gossh.AuthMethod{ gossh.Password(config.SSHPassword), gossh.KeyboardInteractive( ssh.PasswordKeyboardInteractive(config.SSHPassword)), } if config.SSHKeyPath != "" { signer, err := commonssh.FileSigner(config.SSHKeyPath) if err != nil { return nil, err } auth = append(auth, gossh.PublicKeys(signer)) } return &gossh.ClientConfig{ User: config.SSHUser, Auth: auth, }, nil }
func SSHConfigFunc(config SSHConfig) func(multistep.StateBag) (*ssh.ClientConfig, error) { return func(state multistep.StateBag) (*ssh.ClientConfig, error) { auth := []ssh.AuthMethod{ ssh.Password(config.SSHPassword), ssh.KeyboardInteractive( packerssh.PasswordKeyboardInteractive(config.SSHPassword)), } if config.SSHKeyPath != "" { signer, err := sshKeyToSigner(config.SSHKeyPath) if err != nil { return nil, err } auth = append(auth, ssh.PublicKeys(signer)) } return &ssh.ClientConfig{ User: config.SSHUser, Auth: auth, }, nil } }
func ssh_port_forward(local_listener net.Listener, remote_port uint, remote_dest, host, username, password string) error { config := &gossh.ClientConfig{ User: username, Auth: []gossh.AuthMethod{ gossh.Password(password), }, } for { local_connection, err := local_listener.Accept() if err != nil { log.Printf("Local accept failed: %s", err) return err } // Forward to a remote port go forward(local_connection, config, host, remote_dest, remote_port) } return nil }
// SSHConfig returns a function that can be used for the SSH communicator // config for connecting to the specified host via SSH // private_key_file has precedence over password! func SSHConfig(username string, password string, privateKeyFile string) func(multistep.StateBag) (*gossh.ClientConfig, error) { return func(state multistep.StateBag) (*gossh.ClientConfig, error) { if privateKeyFile != "" { // key based auth bytes, err := ioutil.ReadFile(privateKeyFile) if err != nil { return nil, fmt.Errorf("Error setting up SSH config: %s", err) } privateKey := string(bytes) signer, err := gossh.ParsePrivateKey([]byte(privateKey)) if err != nil { return nil, fmt.Errorf("Error setting up SSH config: %s", err) } return &gossh.ClientConfig{ User: username, Auth: []gossh.AuthMethod{ gossh.PublicKeys(signer), }, }, nil } else { // password based auth return &gossh.ClientConfig{ User: username, Auth: []gossh.AuthMethod{ gossh.Password(password), gossh.KeyboardInteractive( ssh.PasswordKeyboardInteractive(password)), }, }, nil } } }