// func that is responsible of setting the session and communicating func sshDispatch(cmd string, user string, ip string, key string, messages chan<- string) { var res string pemBytes, err := ioutil.ReadFile(key) if err != nil { log.Fatal(err) } signer, err := ssh.ParsePrivateKey(pemBytes) if err != nil { log.Fatalf("parse key failed:%v", err) } config := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)}, } conn, err := ssh.Dial("tcp", ip+":22", config) if err != nil { log.Fatalf("dial failed:%v", err) } defer conn.Close() session, err := conn.NewSession() if err != nil { log.Fatalf("session failed:%v", err) } defer session.Close() var stdoutBuf bytes.Buffer session.Stdout = &stdoutBuf err = session.Run(cmd) if err != nil { // upon dispatching a query that can result in Process exited with 1 // it shouldn't completly fail, the thing here is that that OS // was not compatible with that query, so we handle some cases here res += fmt.Sprintf("\nMachine: %v@%v\n", user, ip) if strings.Contains(cmd, "apt_resources") || strings.Contains(cmd, "deb_packages") { res += fmt.Sprintf("Target is RPM based, query won't return anything: %v\n", cmd) } else if strings.Contains(cmd, "rpm_package_files") || strings.Contains(cmd, "rpm_packages") { res += fmt.Sprintf("Target is APT based, query won't return anything: %v\n", cmd) } else { res += fmt.Sprintf("No response for the following query from this machine : %v\n", cmd) } messages <- res } else { res += fmt.Sprintf("\nMachine: %v@%v\n", user, ip) res += stdoutBuf.String() res = string(res[:]) messages <- res } }
func ExampleNewServerConn() { // An SSH server is represented by a ServerConfig, which holds // certificate details and handles authentication of ServerConns. config := &ssh.ServerConfig{ PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { // Should use constant-time compare (or better, salt+hash) in // a production setting. if c.User() == "testuser" && string(pass) == "tiger" { return nil, nil } return nil, fmt.Errorf("password rejected for %q", c.User()) }, } privateBytes, err := ioutil.ReadFile("id_rsa") if err != nil { panic("Failed to load private key") } private, err := ssh.ParsePrivateKey(privateBytes) if err != nil { panic("Failed to parse private key") } config.AddHostKey(private) // Once a ServerConfig has been configured, connections can be // accepted. listener, err := net.Listen("tcp", "0.0.0.0:2022") if err != nil { panic("failed to listen for connection") } nConn, err := listener.Accept() if err != nil { panic("failed to accept incoming connection") } // Before use, a handshake must be performed on the incoming // net.Conn. _, chans, reqs, err := ssh.NewServerConn(nConn, config) if err != nil { panic("failed to handshake") } // The incoming Request channel must be serviced. go ssh.DiscardRequests(reqs) // Service the incoming Channel channel. for newChannel := range chans { // Channels have a type, depending on the application level // protocol intended. In the case of a shell, the type is // "session" and ServerShell may be used to present a simple // terminal interface. if newChannel.ChannelType() != "session" { newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") continue } channel, requests, err := newChannel.Accept() if err != nil { panic("could not accept channel.") } // Sessions have out-of-band requests such as "shell", // "pty-req" and "env". Here we handle only the // "shell" request. go func(in <-chan *ssh.Request) { for req := range in { ok := false switch req.Type { case "shell": ok = true if len(req.Payload) > 0 { // We don't accept any // commands, only the // default shell. ok = false } } req.Reply(ok, nil) } }(requests) term := terminal.NewTerminal(channel, "> ") go func() { defer channel.Close() for { line, err := term.ReadLine() if err != nil { break } fmt.Println(line) } }() } }