• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang readline.String函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/bobappleyard/readline.String函数的典型用法代码示例。如果您正苦于以下问题:Golang String函数的具体用法?Golang String怎么用?Golang String使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了String函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: loaderCreator

// Prompts for input and creates a new loader entry through the API
func loaderCreator(cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("loaderCreator() -> %v", e)
		}
	}()
	var newle mig.LoaderEntry
	fmt.Println("Entering loader creation mode.\nPlease provide the name" +
		" of the new entry")
	newle.Name, err = readline.String("name> ")
	if err != nil {
		panic(err)
	}
	if len(newle.Name) < 3 {
		panic("input name too short")
	}
	fmt.Printf("Name: '%s'\n", newle.Name)
	fmt.Println("Please provide loader key for entry.")
	newle.Key, err = readline.String("key> ")
	if err != nil {
		panic(err)
	}
	fmt.Printf("Key: '%s'\n", newle.Key)
	// Validate the new loader entry before sending it to the API
	err = newle.Validate()
	if err != nil {
		panic(err)
	}
	jsonle, err := json.MarshalIndent(newle, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", jsonle)
	input, err := readline.String("create loader entry? (y/n)> ")
	if err != nil {
		panic(err)
	}
	if input != "y" {
		fmt.Println("abort")
		return
	}
	err = cli.PostNewLoader(newle)
	if err != nil {
		panic(err)
	}
	fmt.Println("New entry successfully created but is disabled")
	return
}
开发者ID:saakaifoundry,项目名称:mig,代码行数:49,代码来源:loader.go


示例2: replCLI

func replCLI(env *Env) {
	defer fmt.Println("\nbye!")
	counter := readline.HistorySize()
	for {
		buf := bytes.Buffer{}
		prompt := fmt.Sprintf("[%d]-> ", counter)
		for {
			l, err := readline.String(prompt)
			if err == io.EOF {
				return
			}
			buf.WriteString(l)
			if validSexp(buf.String()) {
				break
			}
			buf.WriteString("\n")
			prompt = ": "
		}
		result, err := repl(buf.String(), env)
		if err != nil && err != ErrorEOF {
			fmt.Println("Error:", err)
		} else {
			fmt.Println(result)
		}
		readline.AddHistory(buf.String())
		counter++

	}
}
开发者ID:rread,项目名称:rsi,代码行数:29,代码来源:main.go


示例3: main

func main() {
	env := evaluator.BuildEnvironment()

	for {
		l, err := readline.String("> ")
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			break
		}

		f, err := parser.Parse(strings.NewReader(l))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			readline.AddHistory(l)
		}

		r, err := evaluator.Eval(env, f)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
		} else {
			fmt.Println(r)
		}
		readline.AddHistory(l)
	}
}
开发者ID:alanthird,项目名称:gscheme,代码行数:28,代码来源:main.go


示例4: ExampleCleanup

func ExampleCleanup() {
	sigint := make(chan os.Signal, 1)
	signal.Notify(sigint, syscall.SIGINT)

	readline.CatchSigint = false

	var line string
	var err error

	done := make(chan struct{})

	go func() {
		line, err = readline.String("> ")
		close(done)
	}()

	select {
	case <-sigint:
		fmt.Println("\nInterrupted")

		// Restore terminal attributes
		readline.Cleanup()
		// Note that we still have a goroutine reading from Stdin that
		// will terminate when we exit.
		os.Exit(1)
	case <-done:
		fmt.Printf("Read line %s, error %v\n", line, err)
	}
}
开发者ID:ZhuHangpeng,项目名称:mig,代码行数:29,代码来源:example_test.go


示例5: main

/*
func main() {
	flag.Parse()
	go sigHandler()

	rl, err := readline.New("> ")
	if err != nil {
		panic(err)
	}
	defer rl.Close()

	for {
		line, err := rl.Readline()
		if err != nil {
			break
		}
		args := strings.Fields(line)
		if len(args) == 0 {
			continue
		}
		f, ok := cmd[args[0]]
		if ok {
			err := f(args[1:])
			if err != nil {
				log.Println(line, err)
			}
		} else {
			log.Println("Not found:", line)
		}
		stop = false
	}
	fmt.Println("Exiting")
}
*/
func main() {
	flag.Parse()
	go sigHandler()

	for {
		line, err := readline.String("% ")
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Println("error:", err)
			break
		}
		args := strings.Fields(line)
		if len(args) == 0 {
			continue
		}
		f, ok := cmd[args[0]]
		if ok {
			err := f(args[1:])
			if err != nil {
				log.Println(line, err)
			}
		} else {
			log.Println("Not found:", line)
		}
		stop = false
		readline.AddHistory(line)
	}
	fmt.Println("Exiting")
}
开发者ID:taysom,项目名称:va,代码行数:65,代码来源:main.go


示例6: uiLoop

func uiLoop() {
	for {
		line := readline.String("> ")
		rc := uiParseHistory(line)
		if !rc {
			break
		}
	}
}
开发者ID:CrossTheStreams,项目名称:goop,代码行数:9,代码来源:ui.go


示例7: Start

// Starts the controller.
func (c *Controller) Start() int {
	c.welcome()
	c.ChangeWorkingDir("/")

	readline.Completer = c.filenameCompleter
	buffer := bytes.NewBufferString("")
	prompt := ""

	for {
		if buffer.Len() == 0 {
			prompt = c.ps1()
		} else {
			prompt = c.ps2()
		}

		line, err := readline.String(prompt)
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}

		line = strings.TrimSpace(line)
		if strings.ToLower(line) == "q" || strings.ToLower(line) == "exit" {
			return 0
		}
		if strings.HasSuffix(line, "\\") {
			buffer.WriteString(strings.TrimSuffix(line, "\\") + "\n")
		} else {
			if buffer.Len() > 0 {
				buffer.WriteString(line)
				line = buffer.String()
				buffer.Reset()
			}

			parts, err := shlex.Split(line)
			if err != nil {
				panic(err)
			}
			readline.AddHistory(line)

			in := NewInput(parts[0])
			if len(parts) > 1 {
				in.Args = parts[1:]
			}
			c.handleInput(in)
		}
	}

	return 0
}
开发者ID:headzoo,项目名称:etcdsh,代码行数:53,代码来源:controller.go


示例8: interact

// Gets additional suppression patterns, etc. from the user.
func interact(done chan<- string) {
	const prompt = "prolix> "
L:
	for {
		cmd, _ := readline.String(prompt)
		if cmd == "" {
			break L
		}
		readline.AddHistory(cmd)
		unary := unaryRe.FindStringSubmatch(cmd)
		if unary == nil {
			trimmed := strings.TrimSpace(cmd)
			switch trimmed {
			case "quit":
				done <- "quit"
				return
			case "pats":
				printPats()
			case "help":
				printInteractiveHelp()
			default:
				fmt.Println("Unknown command. Try 'help'.")
			}
		} else {
			switch strings.Replace(unary[1], "_", "-", -1) {
			case "ignore-re":
				if importIgnoreRE(unary[2:3]) {
					ignoreRe = append(ignoreRe, unary[2])
				}
			case "ignore-line":
				ignoreLine = append(ignoreLine, unary[2])
			case "ignore-substring":
				ignoreSubstring = append(ignoreSubstring, unary[2])
			case "snippet":
				if importSnippet(unary[2:3]) {
					snippet = append(snippet, unary[2])
				}
			default:
				fmt.Println("Unknown unary command. Try 'help'.")
			}
		}
	}
	done <- ""
}
开发者ID:gaal,项目名称:prolix-go,代码行数:45,代码来源:prolix.go


示例9: CommandParser

func CommandParser() <-chan Command {
	commands := make(chan Command, 1)

	go func() {
		for {
			in, err := readline.String("")
			if err == io.EOF { // Ctrl+D
				commands <- Exit
				break
			} else if err != nil {
				log.Fatal(err)
			}

			commands <- NormalizeCommand(in)
			readline.AddHistory(in)
		}
	}()

	return commands
}
开发者ID:rschmukler,项目名称:looper,代码行数:20,代码来源:input.go


示例10: doPrompt

func doPrompt(s *KinesisStream) {

	moreToRead := true
	for moreToRead {
		line, err := readline.String("Send to Kinesis, <crtl-d> to end: ")
		if err == io.EOF {
			moreToRead = false
		} else if err != nil {
			log.Fatal(err)
		} else {
			resp, err := s.PutLogLine(strings.TrimRight(line, "\n"))
			if err != nil {
				log.Fatal(err)
			}
			if verbose {
				fmt.Println("Response:", awsutil.StringValue(resp))
			}
			readline.AddHistory(line)
		}
	}
}
开发者ID:jdrivas,项目名称:spur,代码行数:21,代码来源:spur.go


示例11: promptLoop

func promptLoop(prompt string, process func(string) error) (err error) {

	errStr := "Error - %s.\n"
	for moreCommands := true; moreCommands; {
		line, err := readline.String(prompt)
		if err == io.EOF {
			moreCommands = false
		} else if err != nil {
			fmt.Printf(errStr, err)
		} else {
			readline.AddHistory(line)
			err = process(line)
			if err == io.EOF {
				moreCommands = false
			} else if err != nil {
				fmt.Printf(errStr, err)
			}
		}
	}
	return nil
}
开发者ID:jdrivas,项目名称:spur,代码行数:21,代码来源:helper.go


示例12: actionLauncher

// actionLauncher prepares an action for launch, either by starting with an empty
// template, or by loading an existing action from the api or the local disk
func actionLauncher(tpl mig.Action, ctx Context) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("actionLauncher() -> %v", e)
		}
	}()
	var a mig.Action
	if tpl.ID == 0 {
		fmt.Println("Entering action launcher with empty template")
		a.SyntaxVersion = mig.ActionVersion
	} else {
		// reinit the fields that we don't reuse
		a.Name = tpl.Name
		a.Target = tpl.Target
		a.Description = tpl.Description
		a.Threat = tpl.Threat
		a.Operations = tpl.Operations
		a.SyntaxVersion = tpl.SyntaxVersion
		fmt.Printf("Entering action launcher using template '%s'\n", a.Name)
	}
	hasTimes := false
	hasSignatures := false

	fmt.Println("Type \x1b[32;1mexit\x1b[0m or press \x1b[32;1mctrl+d\x1b[0m to leave. \x1b[32;1mhelp\x1b[0m may help.")
	prompt := "\x1b[33;1mlauncher>\x1b[0m "
	for {
		// completion
		var symbols = []string{"addoperation", "deloperation", "exit", "help", "init",
			"json", "launch", "load", "details", "filechecker", "netstat",
			"setname", "settarget", "settimes", "sign", "times"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String(prompt)
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "addoperation":
			if len(orders) != 2 {
				fmt.Println("Wrong arguments. Expects 'addoperation <module_name>'")
				fmt.Println("example: addoperation filechecker")
				break
			}
			// attempt to call ParamsCreator from the requested module
			// ParamsCreator takes care of retrieving using input
			var operation mig.Operation
			operation.Module = orders[1]
			if _, ok := mig.AvailableModules[operation.Module]; ok {
				// instanciate and call module parameters creation function
				modRunner := mig.AvailableModules[operation.Module]()
				if _, ok := modRunner.(mig.HasParamsCreator); !ok {
					fmt.Println(operation.Module, "module does not provide a parameters creator.")
					fmt.Println("You can write your action by hand and import it using 'load <file>'")
					break
				}
				operation.Parameters, err = modRunner.(mig.HasParamsCreator).ParamsCreator()
				if err != nil {
					fmt.Printf("Parameters creation failed with error: %v\n", err)
					break
				}
				a.Operations = append(a.Operations, operation)
				opjson, err := json.MarshalIndent(operation, "", "  ")
				if err != nil {
					panic(err)
				}
				fmt.Printf("Inserting %s operation with parameters:\n%s\n", operation.Module, opjson)
			} else {
				fmt.Println("Module", operation.Module, "is not available in this console...")
				fmt.Println("You can write your action by hand and import it using 'load <file>'")
			}
		case "deloperation":
			if len(orders) != 2 {
				fmt.Println("Wrong arguments. Expects 'deloperation <opnum>'")
				fmt.Println("example: deloperation 0")
				break
			}
			opnum, err := strconv.Atoi(orders[1])
			if err != nil || opnum < 0 || opnum > len(a.Operations)-1 {
				fmt.Println("error: <opnum> must be a positive integer between 0 and", len(a.Operations)-1)
				break
			}
			a.Operations = append(a.Operations[:opnum], a.Operations[opnum+1:]...)
		case "details":
			fmt.Printf("ID       %.0f\nName     %s\nTarget   %s\nAuthor   %s <%s>\n"+
				"Revision %.0f\nURL      %s\nThreat Type %s, Level %s, Family %s, Reference %s\n",
//.........这里部分代码省略.........
开发者ID:netantho,项目名称:mig,代码行数:101,代码来源:action_launcher.go


示例13: main

func main() {
	var err error
	fmt.Println("\x1b[32;1m" + `
## ##                                     _.---._     .---.
# # # /-\ ---||  |    /\         __...---' .---. '---'-.   '.
#   #|   | / ||  |   /--\    .-''__.--' _.'( | )'.  '.  '._ :
#   # \_/ ---| \_ \_/    \ .'__-'_ .--'' ._'---'_.-.  '.   '-'.
     ###                         ~ -._ -._''---. -.    '-._   '.
      # |\ |\    /---------|          ~ -.._ _ _ _ ..-_ '.  '-._''--.._
      # | \| \  / |- |__ | |                       -~ -._  '-.  -. '-._''--.._.--''.
     ###|  \  \/  ---__| | |                            ~ ~-.__     -._  '-.__   '. '.
          #####                                               ~~ ~---...__ _    ._ .' '.
          #      /\  --- /-\ |--|----                                    ~  ~--.....--~
          # ### /--\  | |   ||-\  //
          #####/    \ |  \_/ |  \//__
` + "\x1b[0m")

	ctx.Homedir = findHomedir()
	// command line options
	var config = flag.String("c", ctx.Homedir+"/.migconsole", "Load configuration from file")
	var api = flag.String("a", "undef", "API base url (ex: http://localhost:1664/api/v1/)")
	var shortnames = flag.Bool("s", false, "Shorten all agent names to first and last 5 characters)")
	flag.Parse()
	// append a space after completion
	readline.CompletionAppendChar = 0x20

	if *shortnames {
		useShortNames = true
	}
	if *api != "undef" {
		ctx.API.URL = *api
	} else {
		err := gcfg.ReadFileInto(&ctx, *config)
		if err != nil {
			panic(err)
		}
	}
	ctx.GPG.Home, err = findGPGHome(ctx)
	if err != nil {
		panic(err)
	}

	err = printStatus(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("\nConnected to %s. Exit with \x1b[32;1mctrl+d\x1b[0m. Type \x1b[32;1mhelp\x1b[0m for help.\n", ctx.API.URL)
	for {
		// completion
		var symbols = []string{"action", "agent", "command", "help", "exit", "showcfg", "status",
			"search", "where", "and"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String("\x1b[32;1mmig>\x1b[0m ")
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "action":
			if len(orders) == 2 {
				if orders[1] == "new" {
					var a mig.Action
					err = actionLauncher(a, ctx)
				} else {
					err = actionReader(input, ctx)
				}
				if err != nil {
					log.Println(err)
				}
			} else {
				fmt.Println("error: 'action' order takes one argument; " +
					"either 'new' to enter launcher mode, or an action ID to enter reader mode.")
			}
		case "agent":
			err = agentReader(input, ctx)
			if err != nil {
				log.Println(err)
			}
		case "command":
			err = commandReader(input, ctx)
			if err != nil {
				log.Println(err)
			}
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "help":
//.........这里部分代码省略.........
开发者ID:netantho,项目名称:mig,代码行数:101,代码来源:console.go


示例14: REPL

func REPL(c Context) (Context, error) {
	tokens := []string{}
	leftCount := 0
	rightCount := 0

	for {
		prompt := mainPrompt
		if len(tokens) > 0 {
			prompt = incompletePrompt
		}

		line, err := readline.String(prompt)
		if err != nil {
			return nil, err
		}

		if line != "" {
			line = strings.TrimRight(line, "\r\n ")
			readline.AddHistory(line)

			if line == "quit" {
				return c, nil
			}

			temp := Tokenize(line)
			for _, t := range temp {
				if t == "(" || t == "'(" {
					leftCount += 1
				} else if t == ")" {
					rightCount += 1
				}
			}

			tokens = append(tokens, temp...)

			if leftCount == rightCount {
				nodes, err := Parse(tokens)
				if err != nil {
					fmt.Println("error: ", err)
				} else {
					for _, n := range nodes {
						r := n.Eval(c)

						if r.Type() == "error" {
							fmt.Println("error:", r.Value().(string))
							break
						}

						if r != NIL {
							fmt.Println(r)
						}
					}
				}

				leftCount = 0
				rightCount = 0
				tokens = []string{}
			}
		}
	}
}
开发者ID:ktravis,项目名称:sigmo,代码行数:61,代码来源:repl.go


示例15: commandReader

// commandReader retrieves an command from the API using its numerical ID
// and enters prompt mode to analyze it
func commandReader(input string, cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("commandReader() -> %v", e)
		}
	}()
	inputArr := strings.Split(input, " ")
	if len(inputArr) < 2 {
		panic("wrong order format. must be 'command <commandid>'")
	}
	cmdid, err := strconv.ParseFloat(inputArr[1], 64)
	if err != nil {
		panic(err)
	}
	cmd, err := cli.GetCommand(cmdid)
	if err != nil {
		panic(err)
	}

	fmt.Println("Entering command reader mode. Type \x1b[32;1mexit\x1b[0m or press \x1b[32;1mctrl+d\x1b[0m to leave. \x1b[32;1mhelp\x1b[0m may help.")
	fmt.Printf("Command %.0f ran on agent '%s' based on action '%s'\n",
		cmd.ID, cmd.Agent.Name, cmd.Action.Name)
	prompt := fmt.Sprintf("\x1b[36;1mcommand %d>\x1b[0m ", uint64(cmdid)%1000)
	for {
		// completion
		var symbols = []string{"exit", "help", "json", "found", "pretty", "r", "results"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String(prompt)
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "help":
			fmt.Printf(`The following orders are available:
exit		exit this mode
help		show this help
json		show the json of the command
r		refresh the command (get latest version from upstream)
results <found>	print the results. if "found" is set, only print results that have at least one found
`)
		case "json":
			var cjson []byte
			cjson, err = json.MarshalIndent(cmd, "", "  ")
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s\n", cjson)
		case "r":
			cmd, err = cli.GetCommand(cmdid)
			if err != nil {
				panic(err)
			}
			fmt.Println("Reload succeeded")
		case "results":
			found := false
			if len(orders) > 1 {
				if orders[1] == "found" {
					found = true
				} else {
					fmt.Printf("Unknown option '%s'\n", orders[1])
				}
			}
			err = client.PrintCommandResults(cmd, found, false)
			if err != nil {
				panic(err)
			}
		case "":
			break
		default:
			fmt.Printf("Unknown order '%s'. You are in command reader mode. Try `help`.\n", orders[0])
		}
		readline.AddHistory(input)
	}
exit:
	fmt.Printf("\n")
	return
}
开发者ID:Novemburr,项目名称:mig,代码行数:96,代码来源:command_reader.go


示例16: actionReader

// actionReader retrieves an action from the API using its numerical ID
// and enters prompt mode to analyze it
func actionReader(input string, cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("actionReader() -> %v", e)
		}
	}()
	inputArr := strings.Split(input, " ")
	if len(inputArr) < 2 {
		panic("wrong order format. must be 'action <actionid>'")
	}
	aid, err := strconv.ParseFloat(inputArr[1], 64)
	if err != nil {
		panic(err)
	}
	a, _, err := cli.GetAction(aid)
	if err != nil {
		panic(err)
	}
	investigators := investigatorsStringFromAction(a.Investigators, 80)

	fmt.Println("Entering action reader mode. Type \x1b[32;1mexit\x1b[0m or press \x1b[32;1mctrl+d\x1b[0m to leave. \x1b[32;1mhelp\x1b[0m may help.")
	fmt.Printf("Action: '%s'.\nLaunched by '%s' on '%s'.\nStatus '%s'.\n",
		a.Name, investigators, a.StartTime, a.Status)
	a.PrintCounters()
	prompt := fmt.Sprintf("\x1b[31;1maction %d>\x1b[0m ", uint64(aid)%1000)
	for {
		// completion
		var symbols = []string{"command", "copy", "counters", "details", "exit", "grep", "help", "investigators",
			"json", "list", "all", "found", "notfound", "pretty", "r", "results", "times"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String(prompt)
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "command":
			err = commandReader(input, cli)
			if err != nil {
				panic(err)
			}
		case "copy":
			err = actionLauncher(a, cli)
			if err != nil {
				panic(err)
			}
			goto exit
		case "counters":
			a, _, err = cli.GetAction(aid)
			if err != nil {
				panic(err)
			}
			a.PrintCounters()
		case "details":
			actionPrintDetails(a)
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "help":
			fmt.Printf(`The following orders are available:
command <id>	jump to command reader mode for command <id>

copy		enter action launcher mode using current action as template

counters	display the counters of the action

details		display the details of the action, including status & times

exit		exit this mode (also works with ctrl+d)

help		show this help

investigators   print the list of investigators that signed the action

json         	show the json of the action

list <show>	returns the list of commands with their status
		<show>: * set to "all" to get all results (default)
			* set to "found" to only display positive results
			* set to "notfound" for negative results
		list can be followed by a 'filter' pipe:
		ex: ls | grep server1.(dom1|dom2) | grep -v example.net

r		refresh the action (get latest version from upstream)

//.........这里部分代码省略.........
开发者ID:rayyang2000,项目名称:mig,代码行数:101,代码来源:action_reader.go


示例17: main

func main() {
	var err error
	defer func() {
		if e := recover(); e != nil {
			fmt.Fprintf(os.Stderr, "FATAL: %v\n", e)
		}
	}()
	homedir := client.FindHomedir()
	// command line options
	var config = flag.String("c", homedir+"/.migrc", "Load configuration from file")
	var quiet = flag.Bool("q", false, "don't display banners and prompts")
	var showversion = flag.Bool("V", false, "show build version and exit")
	flag.Parse()

	if *showversion {
		fmt.Println(version)
		os.Exit(0)
	}

	// silence extra output
	out := os.Stdout
	if *quiet {
		out.Close()
		out, err = os.Open(os.DevNull)
		if err != nil {
			panic(err)
		}
	}
	defer out.Close()

	fmt.Fprintf(out, "\x1b[32;1m"+banner+"\x1b[0m")

	// append a space after completion
	readline.CompletionAppendChar = 0x20
	// load history
	historyfile := homedir + "/.mig_history"
	fi, err := os.Stat(historyfile)
	if err == nil && fi.Size() > 0 {
		err = readline.LoadHistory(historyfile)
		if err != nil {
			fmt.Fprintf(os.Stderr, "failed to load history from %s\n", historyfile)
		}
	}
	// instanciate an API client
	conf, err := client.ReadConfiguration(*config)
	if err != nil {
		panic(err)
	}
	cli, err := client.NewClient(conf, "console-"+version)
	if err != nil {
		panic(err)
	}
	// print platform status
	err = printStatus(cli)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Fprintf(out, "\nConnected to %s. Exit with \x1b[32;1mctrl+d\x1b[0m. Type \x1b[32;1mhelp\x1b[0m for help.\n", cli.Conf.API.URL)
	for {
		// completion
		var symbols = []string{"action", "agent", "create", "command", "help", "history",
			"exit", "showcfg", "status", "investigator", "search", "where", "and"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String("\x1b[32;1mmig>\x1b[0m ")
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "action":
			if len(orders) == 2 {
				err = actionReader(input, cli)
				if err != nil {
					log.Println(err)
				}
			} else {
				fmt.Println("error: missing action id in 'action <id>'")
			}
		case "agent":
			err = agentReader(input, cli)
			if err != nil {
				log.Println(err)
			}
		case "create":
			if len(orders) == 2 {
				switch orders[1] {
				case "action":
//.........这里部分代码省略.........
开发者ID:Novemburr,项目名称:mig,代码行数:101,代码来源:console.go


示例18: manifestReader

// manifestReader is used to manipulate API manifests
func manifestReader(input string, cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("manifestReader() -> %v", e)
		}
	}()
	inputArr := strings.Split(input, " ")
	if len(inputArr) < 2 {
		panic("wrong order format. must be 'manifest <manifestid>'")
	}
	mid, err := strconv.ParseFloat(inputArr[1], 64)
	if err != nil {
		panic(err)
	}
	mr, err := cli.GetManifestRecord(mid)
	if err != nil {
		panic(err)
	}

	fmt.Println("Entering manifest reader mode. Type \x1b[32;1mexit\x1b[0m or press \x1b[32;1mctrl+d\x1b[0m to leave. \x1b[32;1mhelp\x1b[0m may help.")
	fmt.Printf("Manifest: '%s'.\nStatus '%s'.\n", mr.Name, mr.Status)

	prompt := fmt.Sprintf("\x1b[31;1mmanifest %d>\x1b[0m ", uint64(mid)%1000)
	for {
		var symbols = []string{"disable", "entry", "exit", "help", "json", "r", "reset", "sign"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String(prompt)
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "disable":
			err = cli.ManifestRecordStatus(mr, "disabled")
			if err != nil {
				panic(err)
			}
			fmt.Println("Manifest record has been disabled")
		case "entry":
			mre, err := mr.ManifestResponse()
			if err != nil {
				panic(err)
			}
			buf, err := json.MarshalIndent(mre, "", "  ")
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s\n", buf)
		case "help":
			fmt.Printf(`The following orders are avialable:
disable         disables manifest and prevents future use

entry           show the manifest for this record as would be sent to a loader

help            show this help

exit            exit this mode (also works with ctrl+d)

json            show json of manifest record stored in database

loaders         show known loader entries that will match this manifest

r               refresh the manifest (get latest version from database)

reset           reset manifest status (marks manifest as staged, removes signatures)

sign            add a signature to the manifest record
`)
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "json":
			tmpmr := mr
			if len(tmpmr.Content) > 0 {
				tmpmr.Content = "..."
			} else {
				tmpmr.Content = "None"
			}
			jsonmr, err := json.MarshalIndent(tmpmr, "", "  ")
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s\n", jsonmr)
		case "loaders":
			ldrs, err := cli.GetManifestLoaders(mid)
			if err != nil {
//.........这里部分代码省略.........
开发者ID:saakaifoundry,项目名称:mig,代码行数:101,代码来源:manifest.go


示例19: manifestCreator

// Prompts for input and creates a new manifest record through the API
func manifestCreator(cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("manifestCreator() -> %v", e)
		}
	}()
	var newmr mig.ManifestRecord
	fmt.Println("Entering manifest creation mode.\nPlease provide the name" +
		" of the new manifest")
	newmr.Name, err = readline.String("name> ")
	if err != nil {
		panic(err)
	}
	if len(newmr.Name) < 3 {
		panic("input name too short")
	}
	fmt.Printf("Name: '%s'\n", newmr.Name)
	fmt.Println("Please provide loader targeting string for manifest.")
	newmr.Target, err = readline.String("target> ")
	if err != nil {
		panic(err)
	}
	fmt.Printf("Target: '%s'\n", newmr.Target)
	fmt.Println("Please enter path to new manifest archive content.")
	arcpath, err := readline.String("contentpath> ")
	if err != nil {
		panic(err)
	}
	// Load the content into the manifest record from the specified path,
	// we assume the archive is a gzip compressed tar file; if not it will
	// fail during validation later on.
	err = newmr.ContentFromFile(arcpath)
	if err != nil {
		panic(err)
	}
	newmr.Status = "staged"
	// Validate the new manifest record before sending it to the API
	err = newmr.Validate()
	if err != nil {
		panic(err)
	}
	tmpmr := newmr
	if len(tmpmr.Content) > 0 {
		tmpmr.Content = "..."
	} else {
		tmpmr.Content = "None"
	}
	jsonmr, err := json.MarshalIndent(tmpmr, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", jsonmr)
	input, err := readline.String("create manifest? (y/n)> ")
	if err != nil {
		panic(err)
	}
	if input != "y" {
		fmt.Println("abort")
		return
	}
	err = cli.PostNewManifest(newmr)
	if err != nil {
		panic(err)
	}
	fmt.Println("Manifest successfully created")
	return
}
开发者ID:saakaifoundry,项目名称:mig,代码行数:68,代码来源:manifest.go


示例20: actionReader

// actionReader retrieves an action from the API using its numerical ID
// and enters prompt mode to analyze it
func actionReader(input string, ctx Context) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("actionReader() -> %v", e)
		}
	}()
	inputArr := strings.Split(input, " ")
	if len(inputArr) < 2 {
		panic("wrong order format. must be 'action <actionid>'")
	}
	aid := inputArr[1]
	a, links, err := getAction(aid, ctx)
	if err != nil {
		panic(err)
	}
	investigators := investigatorsStringFromAction(a.Investigators, 80)

	fmt.Println("Entering action reader mode. Type \x1b[32;1mexit\x1b[0m or press \x1b[32;1mctrl+d\x1b[0m to leave. \x1b[32;1mhelp\x1b[0m may help.")
	fmt.Printf("Action: '%s'.\nLaunched by '%s' on '%s'.\nStatus '%s'.\n",
		a.Name, investigators, a.StartTime, a.Status)
	prompt := "\x1b[31;1maction " + aid[len(aid)-3:len(aid)] + ">\x1b[0m "
	for {
		// completion
		var symbols = []string{"command", "copy", "counters", "details", "exit", "foundsomething", "foundnothing",
			"grep", "help", "investigators", "json", "ls", "found", "pretty", "r", "results", "times"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String(prompt)
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "command":
			err = commandReader(input, ctx)
			if err != nil {
				panic(err)
			}
		case "copy":
			err = actionLauncher(a, ctx)
			if err != nil {
				panic(err)
			}
			goto exit
		case "counters":
			fmt.Printf("Sent:\t\t%d\nReturned:\t%d\nDone:\t\t%d\n"+
				"Cancelled:\t%d\nFailed:\t\t%d\nTimeout:\t%d\n",
				a.Counters.Sent, a.Counters.Returned, a.Counters.Done,
				a.Counters.Cancelled, a.Counters.Failed, a.Counters.TimeOut)
		case "details":
			actionPrintDetails(a)
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "foundsomething":
			err = searchFoundAnything(a, true, ctx)
			if err != nil {
				panic(err)
			}
		case "foundnothing":
			err = searchFoundAnything(a, false, ctx)
			if err != nil {
				panic(err)
			}
		case "help":
			fmt.Printf(`The following orders are available:
command <id>	jump to command reader mode for command <id>
copy		enter action launcher mode using current action as template
counters	display the counters of the action
exit		exit this mode
foundsomething	list commands and agents that have found something
foundnothing	list commands and agents that have found nothing
help		show this help
investigators   print the list of investigators that signed the action
json         	show the json of the action
ls <filter>	returns the list of commands with their status
		'filter' is a pipe separated string of filter:
		ex: ls | grep server1.(dom1|dom2) | grep -v example.net
details		display the details of the action, including status & times
r		refresh the action (get latest version from upstream)
times		show the various timestamps of the action
`)
		case "investigators":
			for _, i := range a.Investigators {
				fmt.Println(i.Name, "- Key ID:", i.PGPFingerprint)
			}
//.........这里部分代码省略.........
开发者ID:netantho,项目名称:mig,代码行数:101,代码来源:action_reader.go



注:本文中的github.com/bobappleyard/readline.String函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang matrix.Zeros函数代码示例发布时间:2022-05-24
下一篇:
Golang readline.AddHistory函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap