コード例 #1
0
ファイル: main_test.go プロジェクト: golang-devops/go-psexec
func setupClient(clientPemFile string) (*client.Client, error) {
	pvtKey, err := shared.ReadPemKey(clientPemFile)
	if err != nil {
		return nil, err
	}
	return client.New(pvtKey), nil
}
コード例 #2
0
ファイル: main.go プロジェクト: golang-devops/go-psexec
func execute(fireAndForget bool, onFeedback func(fb string), server, executor, clientPemPath, exe string, args ...string) error {
	pvtKey, err := shared.ReadPemKey(clientPemPath)
	if err != nil {
		return fmt.Errorf("Cannot read client pem file, error: %s", err.Error())
	}

	c := client.New(pvtKey)

	session, err := c.RequestNewSession(server)
	if err != nil {
		return fmt.Errorf("Unable to create new session, error: %s", err.Error())
	}

	onFeedback(fmt.Sprintf("Using session id: %d\n", session.SessionId()))

	workingDir := ""
	builder := getExecutorExecRequestBuilder(session, executor)
	resp, err := builder.Exe(exe).WorkingDir(workingDir).Args(args...).BuildAndDoRequest()
	if err != nil {
		return err
	}

	if fireAndForget {
		onFeedback("Using fire-and-forget mode so the command will continue in the background.")
		return nil
	}

	responseChannel, errChannel := resp.TextResponseChannel()

	allErrors := []error{}
outerFor:
	for {
		select {
		case feedbackLine, ok := <-responseChannel:
			if !ok {
				break outerFor
			}
			onFeedback(feedbackLine)
		case errLine, ok := <-errChannel:
			if !ok {
				break outerFor
			}
			allErrors = append(allErrors, errLine)
		}
	}

	if len(allErrors) > 0 {
		errStrs := []string{}
		for _, e := range allErrors {
			errStrs = append(errStrs, e.Error())
		}
		return fmt.Errorf("ERRORS WERE: %s", strings.Join(errStrs, "\\n"))
	}

	return nil
}
コード例 #3
0
func testingGetNewSessionFileSystem() (SessionFileSystem, error) {
	clientPemFile := os.ExpandEnv(`$GOPATH/src/github.com/golang-devops/go-psexec/client/testdata/test_client.pem`)
	//TODO: Explicitly start a localhost server too and perhaps use another port to not conflict with "default" port of actual server. Refer to server `main_test.go` file method `TestHighLoad` in the `a.Run(logger)` call for an example
	serverUrl := "http://localhost:62677"

	clientPvtKey, err := shared.ReadPemKey(clientPemFile)
	if err != nil {
		return nil, err
	}

	client := New(clientPvtKey)

	tmpSession, err := client.RequestNewSession(serverUrl)
	if err != nil {
		return nil, err
	}

	return NewSessionFileSystem(tmpSession.(*session)), nil
}
コード例 #4
0
ファイル: app.go プロジェクト: golang-devops/go-psexec
func (a *app) Run(logger service.Logger) {
	var logFilePath string
	usr, err := user.Current()
	if err == nil {
		logFilePath = filepath.Join(usr.HomeDir, ".config/go-psexec/server-hidden.log")
	} else {
		logFilePath = "server-hidden.log"
	}

	rollingFile := &lumberjack.Logger{
		Filename:   logFilePath,
		MaxSize:    20, // megabytes
		MaxBackups: 20,
		MaxAge:     28, //days
	}

	apex.SetLevel(apex.DebugLevel) //Global level
	apex.SetHandler(json.New(rollingFile))

	tmpLogger := &defaultLogger{
		logger,
		apex.WithField("exe", filepath.Base(os.Args[0])),
	}
	a.logger = tmpLogger

	defer func() {
		if r := recover(); r != nil {
			a.logger.Errorf("Panic recovery in service RUN function: %T %+v", r, r)
		}
	}()

	a.logger.Infof("Running server version %s", TempVersion)

	a.gracefulTimeout = 30 * time.Second //Because a command could be busy executing

	pvtKey, err := shared.ReadPemKey(*serverPemFlag)
	if err != nil {
		logger.Errorf("Cannot read server pem file, error: %s. Exiting server.", err.Error())
		return
	}
	a.privateKey = pvtKey

	checksumsSvc := checksums.New()
	handlerServices := &HandlerServices{
		FilePathSummaries: filepath_summary.New(checksumsSvc),
	}

	a.h = &handler{logger, a.privateKey, handlerServices}

	allowedKeys, err := shared.LoadAllowedPublicKeysFile(*allowedPublicKeysFileFlag)
	if err != nil {
		logger.Errorf("Cannot read allowed public keys, error: %s. Exiting server.", err.Error())
		return
	}
	if len(allowedKeys) == 0 {
		logger.Errorf("Allowed public key file '%s' was read but contains no keys. Exiting server.", *allowedPublicKeysFileFlag)
		return
	}

	a.setAllowedPublicKeys(allowedKeys)

	watcher, err := shared.StartWatcher(*allowedPublicKeysFileFlag, a)
	if err != nil {

	} else {
		a.watcherPublicKeys = watcher
	}

	e := echo.New()
	if a.debugMode {
		e.SetDebug(true)
	}

	e.Use(middleware.Recover())
	if a.accessLogger {
		loggerCfg := middleware.DefaultLoggerConfig
		loggerCfg.Output = tmpLogger
		e.Use(middleware.LoggerWithConfig(loggerCfg))
	}

	t := &htmlTemplateRenderer{}
	e.SetRenderer(t)

	// Unrestricted group
	e.POST("/token", a.h.handleGenerateTokenFunc)
	e.GET("/webui", a.h.handleWebUIFunc)

	// Restricted group
	r := e.Group("/auth")
	r.Use(GetClientPubkey())
	r.GET("/ping", a.h.handlePingFunc)
	r.GET("/version", a.h.handleVersionFunc)
	r.POST("/stream", a.h.handleStreamFunc)
	r.POST("/start", a.h.handleStartFunc)
	r.POST("/upload-tar", a.h.handleUploadTarFunc)
	r.GET("/download-tar", a.h.handleDownloadTarFunc)
	r.POST("/delete", a.h.handleDeleteFunc)
	r.POST("/move", a.h.handleMoveFunc)
	r.POST("/copy", a.h.handleCopyFunc)
	r.POST("/symlink", a.h.handleSymlinkFunc)
	r.GET("/stats", a.h.handleStatsFunc)
	r.GET("/path-summary", a.h.handlePathSummaryFunc)
	r.GET("/get-temp-dir", a.h.handleGetTempDirFunc)
	r.GET("/get-os-type", a.h.handleGetOsTypeFunc)

	a.logger.Infof("Now serving on '%s'", *addressFlag)

	server := standard.New(*addressFlag)
	server.SetHandler(e)
	server.SetLogger(e.Logger())
	if e.Debug() {
		e.Logger().Debug("running in debug mode")
	}

	a.srv = &graceful.Server{
		Timeout: a.gracefulTimeout,
		Server:  server.Server,
	}

	a.registerInterruptSignal()

	err = a.srv.ListenAndServe()
	if err != nil {
		if !strings.Contains(err.Error(), "closed network connection") {
			logger.Errorf("Unable to ListenAndServe, error: %s", err.Error())
			time.Sleep(time.Second) //Sleep a second to give log time to write out
		}
	}
}