func makeConfig(user string, password string, privateKey string) (config *ssh.ClientConfig) { if password == "" && user == "" { log.Fatal("No password or private key available") } config = &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ ssh.Password(password), }, } if privateKey != "" { log.Println(privateKey) signer, err := ssh.ParsePrivateKey([]byte(privateKey)) if err != nil { log.Fatalf("ssh.ParsePrivateKey error:%v", err) } clientkey := ssh.PublicKeys(signer) config = &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ clientkey, }, } } return }
func main() { if len(os.Args) != 5 { fmt.Fprintf(os.Stderr, "Usage: %s <host> <username> <password> <remote name>\n", os.Args[0]) os.Exit(1) } conn, err := sshcp.NewConn( os.Args[1], os.Args[2], os.Args[4], ssh.Password(os.Args[3]), ) if err != nil { fmt.Fprintf(os.Stderr, "could not open connection: %s", err) return } defer conn.Close() _, err = io.Copy(conn, os.Stdin) if err != nil { fmt.Fprintf(os.Stderr, "error copying data: %s", err) return } fmt.Fprintln(os.Stderr, "done") }
func NewNativeConfig(user string, auth *Auth) (ssh.ClientConfig, error) { var ( authMethods []ssh.AuthMethod ) for _, k := range auth.Keys { key, err := ioutil.ReadFile(k) if err != nil { return ssh.ClientConfig{}, err } privateKey, err := ssh.ParsePrivateKey(key) if err != nil { return ssh.ClientConfig{}, err } authMethods = append(authMethods, ssh.PublicKeys(privateKey)) } for _, p := range auth.Passwords { authMethods = append(authMethods, ssh.Password(p)) } return ssh.ClientConfig{ User: user, Auth: authMethods, }, nil }
func ExampleSession_RequestPty() { // Create client config config := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password("password"), }, } // Connect to ssh server conn, err := ssh.Dial("tcp", "localhost:22", config) if err != nil { log.Fatalf("unable to connect: %s", err) } defer conn.Close() // Create a session session, err := conn.NewSession() if err != nil { log.Fatalf("unable to create session: %s", err) } defer session.Close() // Set up terminal modes modes := ssh.TerminalModes{ ssh.ECHO: 0, // disable echoing ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud } // Request pseudo terminal if err := session.RequestPty("xterm", 80, 40, modes); err != nil { log.Fatalf("request for pseudo terminal failed: %s", err) } // Start remote shell if err := session.Shell(); err != nil { log.Fatalf("failed to start shell: %s", err) } }
// connects to remote server using ClientSSH struct and returns *ssh.Session func (ssh_conf *ClientSSH) connect() (*ssh.Session, error) { // auths holds the detected ssh auth methods auths := []ssh.AuthMethod{} // figure out what auths are requested, what is supported if ssh_conf.Password != "" { auths = append(auths, ssh.Password(ssh_conf.Password)) } if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)) defer sshAgent.Close() } if pubkey, err := getKeyFile(ssh_conf.Key); err == nil { auths = append(auths, ssh.PublicKeys(pubkey)) } config := &ssh.ClientConfig{ User: ssh_conf.User, Auth: auths, } client, err := ssh.Dial("tcp", ssh_conf.Server+":"+ssh_conf.Port, config) if err != nil { return nil, err } session, err := client.NewSession() if err != nil { return nil, err } return session, nil }
func TestHandshakeTimeout(t *testing.T) { clientConfig := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password("pass"), }, } address := newMockBrokenServer(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, HandshakeTimeout: 50 * time.Millisecond, } _, err := New(address, config) if err != ErrHandshakeTimeout { // Note: there's another error that can come back from this call: // ssh: handshake failed: EOF // This should appear in cases where the handshake fails because of // malformed (or no) data sent back by the server, but should not happen // in a timeout scenario. t.Fatalf("Expected handshake timeout, got: %s", err) } }
func ExampleDial() { // An SSH client is represented with a ClientConn. Currently only // the "password" authentication method is supported. // // To authenticate with the remote server you must pass at least one // implementation of AuthMethod via the Auth field in ClientConfig. config := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password("yourpassword"), }, } client, err := ssh.Dial("tcp", "yourserver.com:22", config) if err != nil { panic("Failed to dial: " + err.Error()) } // Each ClientConn can support multiple interactive sessions, // represented by a Session. session, err := client.NewSession() if err != nil { panic("Failed to create session: " + err.Error()) } defer session.Close() // 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("/usr/bin/whoami"); err != nil { panic("Failed to run: " + err.Error()) } fmt.Println(b.String()) }
func (suite *ServerSuite) TestHandlerError() { // Configure client connection config := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password("bandit"), }, } // Create client connection client, err := ssh.Dial("tcp", "127.0.0.1:9022", config) if err != nil { suite.Fail(err.Error()) return } defer client.Close() // Open channel channel, requests, err := client.OpenChannel("/bad", []byte{}) if err != nil { suite.Fail(err.Error()) return } go ssh.DiscardRequests(requests) defer channel.Close() }
func DownLoadDirectoryRecurrsively(hostAndPort string, username string, password string, remoteSourceDirectory string, localTargetDirectory string) error { remoteSourceDirectoryLength := len(remoteSourceDirectory) authMethodSlice := make([]ssh.AuthMethod, 0) authMethodSlice = append(authMethodSlice, ssh.Password(password)) clientConfig := ssh.ClientConfig{ User: username, Auth: authMethodSlice, } connection, err := ssh.Dial("tcp", hostAndPort, &clientConfig) if err != nil { return err } defer connection.Close() // open an SFTP session over an existing ssh connection. client, err := sftp.NewClient(connection) if err != nil { return err } defer client.Close() // walk a directory walk := client.Walk(remoteSourceDirectory) for walk.Step() { if err := walk.Err(); err != nil { return err } if walk.Stat().IsDir() { directoryPath := localTargetDirectory + walk.Path()[remoteSourceDirectoryLength:] if err := os.MkdirAll(directoryPath, os.ModePerm); err != nil { return err } } else { filePath := localTargetDirectory + walk.Path()[remoteSourceDirectoryLength:] file, err := client.Open(walk.Path()) if err != nil { return err } defer file.Close() outputFile, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, os.ModePerm) if err != nil { return err } defer outputFile.Close() _, err = file.WriteTo(outputFile) if err != nil { return err } } } return nil }
func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) { config := state.Get("config").(*Config) var privateKey string var auth []gossh.AuthMethod if config.Comm.SSHPassword != "" { auth = []gossh.AuthMethod{ gossh.Password(config.Comm.SSHPassword), gossh.KeyboardInteractive( ssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)), } } if config.Comm.SSHPrivateKey != "" { if priv, ok := state.GetOk("privateKey"); ok { privateKey = priv.(string) } signer, err := gossh.ParsePrivateKey([]byte(privateKey)) if err != nil { return nil, fmt.Errorf("Error setting up SSH config: %s", err) } if err != nil { return nil, err } auth = append(auth, gossh.PublicKeys(signer)) } return &gossh.ClientConfig{ User: config.Comm.SSHUsername, Auth: auth, }, nil }
func main() { config := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password("minhaSenha"), }, } client, err := ssh.Dial("tcp", "meuservidor.com:22", config) if err != nil { panic("Failed to dial: " + err.Error()) } session, err := client.NewSession() if err != nil { panic("Failed to create session: " + err.Error()) } defer session.Close() 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 (S *SshParm) Connect() (*ssh.Client, error) { var ( cfg *ssh.ClientConfig ) if S.SSHAuthType == SSHAuthType_Certificate { cfg = &ssh.ClientConfig{ User: S.SSHUser, Auth: []ssh.AuthMethod{ PublicKeyFile(S.SSHKeyLocation), }, } } else { cfg = &ssh.ClientConfig{ User: S.SSHUser, Auth: []ssh.AuthMethod{ ssh.Password(S.SSHPassword), }, } } client, e := ssh.Dial("tcp", S.SSHHost, cfg) return client, e }
// New returns a new SFTP remote Cache implementated. func New(server, username, password, key string) (cache.Cache, error) { config := &ssh.ClientConfig{ Timeout: time.Minute * 5, User: username, Auth: []ssh.AuthMethod{ ssh.Password(password), }, } // private key authentication takes precedence if key != "" { signer, err := ssh.ParsePrivateKey([]byte(key)) if err != nil { return nil, err } config.Auth[0] = ssh.PublicKeys(signer) } // create the ssh connection and client client, err := ssh.Dial("tcp", server, config) if err != nil { return nil, err } // open the sftp session using the ssh connection sftp, err := sftp.NewClient(client) if err != nil { client.Close() return nil, err } return &cacher{sftp, client}, nil }
//ClientPassAuth provides a means of returning a ssh.Client and a Authentication function for a one time authentication procedure func ClientPassAuth(addr string, dial, server time.Duration, cb MetaFunc) PasswordAuthCallback { reqs := make(chan struct{}) return func(meta ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { config := &ssh.ClientConfig{} config.User = meta.User() config.Auth = []ssh.AuthMethod{ ssh.Password(string(pass)), } cl, err := DialClient(dial, server, addr, config, reqs) if cb != nil { cb(err, meta, pass, &SSHClient{ Client: cl, Meta: meta, Pass: pass, }) } if err != nil { go func() { reqs <- struct{}{} }() return nil, err } close(reqs) return nil, nil } }
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 NewConnection(host string, port int, username string, password string, key_path string) (*ssh.Client, error) { var config *ssh.ClientConfig if USEKEY { public_key, err := getKeyFromFile(key_path) if err != nil { log.Panic(err) } config = &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.PublicKeys(public_key), }, } } else { config = &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.Password(password), }, } } client, err := ssh.Dial("tcp", host+":"+strconv.Itoa(port), config) if err != nil { panic("Failed to dial: " + err.Error()) } // Each ClientConn can support multiple interactive sessions, // represented by a Session. return client, err }
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) } cmd := &packer.RemoteCmd{ Command: "echo foo", Stdout: new(bytes.Buffer), } client.Start(cmd) }
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)), } if d.PrivateKey != "" { signer, err := commonssh.FileSigner(d.PrivateKey) if err != nil { return err } auth = append(auth, gossh.PublicKeys(signer)) } sshConfig := &ssh.Config{ Connection: ssh.ConnectFunc("tcp", address), SSHConfig: &gossh.ClientConfig{ User: d.Username, Auth: auth, }, } comm, err := ssh.New(address, sshConfig) if err != nil { return err } d.comm = comm return nil }
func main() { flag.Parse() results := make(chan string, 10) timeout := time.After(65 * time.Second) config := &ssh.ClientConfig{ User: "******", //Auth: []ssh.AuthMethod{makeKeyring()}, Auth: []ssh.AuthMethod{ssh.Password("vagrant")}, } cmds := ParseCommands(*cmdsfile) for _, cmd := range cmds { go func(command *Cmd) { results <- executeCmd(command.Command, command.Host, config) }(cmd) } for i := 0; i < len(cmds); i++ { select { case res := <-results: fmt.Print(res) case <-timeout: fmt.Println("Timed out!") return } } }
func (ih *InputHandler) createSession(config *InputEntry) (session *ssh.Session, err error) { var authMethod []ssh.AuthMethod var key *ssh.Signer if !config.Cred.IsPasswordAuth() { key, err = ih.parsePrivateKey(config.Cred.Identity) if err != nil { return } authMethod = []ssh.AuthMethod{ssh.PublicKeys(*key)} } else { authMethod = []ssh.AuthMethod{ssh.Password(config.Cred.Pass)} } sshConfig := new(ssh.ClientConfig) sshConfig.User = config.Cred.User sshConfig.Auth = authMethod port := uint16(22) if config.Port != 0 { port = config.Port } hostNameString := fmt.Sprintf("%s:%d", config.Host, port) client, err := ssh.Dial("tcp", hostNameString, sshConfig) if err != nil { return } session, err = client.NewSession() return }
func ExampleClient_Listen() { config := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password("password"), }, } // Dial your ssh server. conn, err := ssh.Dial("tcp", "localhost:22", config) if err != nil { log.Fatalf("unable to connect: %s", err) } defer conn.Close() // Request the remote side to open port 8080 on all interfaces. l, err := conn.Listen("tcp", "0.0.0.0:8080") if err != nil { log.Fatalf("unable to register tcp forward: %v", err) } defer l.Close() // Serve HTTP with your SSH server acting as a reverse proxy. http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { fmt.Fprintf(resp, "Hello world!\n") })) }
func Client(ip_port, user, password string, command map[string]string) { PassWd := []ssh.AuthMethod{ssh.Password(password)} Conf := ssh.ClientConfig{User: user, Auth: PassWd} Client, err := ssh.Dial("tcp", ip_port, &Conf) if err == nil { fmt.Println(ip_port, "connect status:success") } else { fmt.Print(ip_port, "connect error:", err) return } defer Client.Close() for _, cmd := range command { if session, err := Client.NewSession(); err == nil { defer session.Close() var Result bytes.Buffer session.Stderr = &Result session.Stdout = &Result err = session.Run(cmd) if err == nil { fmt.Println(ip_port, "run command:", cmd, "run status:Ok") } else { fmt.Println(ip_port, "run error:", err) } fmt.Println(ip_port, "run result:\n", Result.String()) } } }
func buildSSHClientConfig(opts sshClientConfigOpts) (*ssh.ClientConfig, error) { conf := &ssh.ClientConfig{ User: opts.user, } if opts.privateKey != "" { pubKeyAuth, err := readPrivateKey(opts.privateKey) if err != nil { return nil, err } conf.Auth = append(conf.Auth, pubKeyAuth) } if opts.password != "" { conf.Auth = append(conf.Auth, ssh.Password(opts.password)) conf.Auth = append(conf.Auth, ssh.KeyboardInteractive( PasswordKeyboardInteractive(opts.password))) } if opts.sshAgent != nil { conf.Auth = append(conf.Auth, opts.sshAgent.Auth()) } return conf, nil }
func main() { sshConfig := &ssh.ClientConfig{ Config: ssh.Config{ Ciphers: []string{"aes128-cbc", "hmac-sha1"}, }, User: "******", Auth: []ssh.AuthMethod{ssh.Password("mypass")}, } s, err := netconf.DialSSH("1.1.1.1", sshConfig) if err != nil { log.Fatal(err) } defer s.Close() fmt.Println(s.ServerCapabilities) fmt.Println(s.SessionID) // Sends raw XML reply, err := s.Exec(netconf.RawMethod("<get-chassis-inventory/>")) if err != nil { panic(err) } fmt.Printf("Reply: %+v", reply) }
func executeCmd(cmd, hostname string) string { // return fmt.Sprintf("executing %v on %v\n", cmd, hostname) config := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ssh.Password("bob2")}, Config: ssh.Config{Ciphers: []string{"aes192-ctr"}}, } fmt.Printf("executing %v on %v\n", cmd, hostname) client, err := ssh.Dial("tcp", hostname, config) if err != nil { fmt.Println(err) } if client == nil { fmt.Printf("Connection to %v failed\n", hostname) return "" } session, err := client.NewSession() if err != err { panic(err) } defer session.Close() var stdoutBuf bytes.Buffer session.Stdout = &stdoutBuf err = session.Start(cmd) if err != nil { fmt.Printf("Session failed with error: %v\n", err) } session.Wait() fmt.Printf("DONE: %v on %v\n", cmd, hostname) return hostname + ": " + stdoutBuf.String() }
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, }, } comm, err := ssh.New(address, sshConfig) if err != nil { return err } d.comm = comm return nil }
// Simply waits for ssh to come up func waitForVmSsh(d *schema.ResourceData) error { l := log.New(os.Stderr, "", 0) l.Printf("Waiting for VM ssh: %s", d.Get("name")) config := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ ssh.Password(d.Get("root_password").(string)), }, } for { select { case <-time.After(waitForVM * time.Second): return fmt.Errorf("VM ssh wasn't up in %d seconds", waitForVM) case <-time.Tick(vmCheckInterval * time.Second): conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", d.Get("ipv4")), config) if err != nil { if strings.Contains(err.Error(), "connection refused") { l.Println("SSH isn't up yet") continue } else { l.Printf("SSH Error, ignored: %s", err.Error()) continue } } conn.Close() l.Println("SSH alive and kicking") return nil } } return errors.New("Ssh wait should never get here") }
// SSHConfig returns a function that can be used for the SSH communicator // config for connecting to the instance created over SSH using the private key // or password. func SSHConfig(username, password string) func(multistep.StateBag) (*ssh.ClientConfig, error) { return func(state multistep.StateBag) (*ssh.ClientConfig, error) { privateKey, hasKey := state.GetOk("privateKey") if hasKey { signer, err := ssh.ParsePrivateKey([]byte(privateKey.(string))) if err != nil { return nil, fmt.Errorf("Error setting up SSH config: %s", err) } return &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.PublicKeys(signer), }, }, nil } else { return &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.Password(password), ssh.KeyboardInteractive( packerssh.PasswordKeyboardInteractive(password)), }}, nil } } }
// execute command over SSH with user / password authentication func executeSSHCommand(command string, d *Driver) error { log.Debugf("Execute executeSSHCommand: %s", command) config := &cryptossh.ClientConfig{ User: d.SSHUser, Auth: []cryptossh.AuthMethod{ cryptossh.Password(d.SSHPassword), }, } client, err := cryptossh.Dial("tcp", fmt.Sprintf("%s:%d", d.IPAddress, d.SSHPort), config) if err != nil { log.Debugf("Failed to dial:", err) return err } session, err := client.NewSession() if err != nil { log.Debugf("Failed to create session: " + err.Error()) return err } defer session.Close() var b bytes.Buffer session.Stdout = &b if err := session.Run(command); err != nil { log.Debugf("Failed to run: " + err.Error()) return err } log.Debugf("Stdout from executeSSHCommand: %s", b.String()) return nil }
func getAuth(args []string) ssh.AuthMethod { switch len(args) { case 3: var pass string fmt.Print("Password: "******"%s\n", &pass) return ssh.Password(pass) case 4: pemBytes, err := ioutil.ReadFile(args[3]) if err != nil { log.Fatal(err) } signer, err := ssh.ParsePrivateKey(pemBytes) if err != nil { log.Fatalf("parse key failed:%v", err) } return ssh.PublicKeys(signer) default: log.Fatalf("Usage: %s <user> <host:port> <(optional) location of .pem file>", os.Args[0]) return nil } }