当前位置: 首页>>代码示例>>Golang>>正文


Golang client.Client类代码示例

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


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

示例1: runSearchQuery

// runSearchQuery executes a search string against the API
func runSearchQuery(sp searchParameters, cli client.Client) (items []cljs.Item, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("runSearchQuery() -> %v", e)
		}
	}()
	fmt.Println("Search query:", sp.query)
	target := sp.query
	resource, err := cli.GetAPIResource(target)
	if err != nil {
		panic(err)
	}
	items = resource.Collection.Items
	return
}
开发者ID:Novemburr,项目名称:mig,代码行数:16,代码来源:search.go

示例2: printInvestigatorLastActions

func printInvestigatorLastActions(iid float64, limit int, cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("printInvestigatorLastActions() -> %v", e)
		}
	}()
	target := fmt.Sprintf("search?type=action&investigatorid=%.0f&limit=%d", iid, limit)
	resource, err := cli.GetAPIResource(target)
	if err != nil {
		panic(err)
	}
	fmt.Printf("-------  ID  ------- + --------    Action Name ------- + ----------- Target   ---------- + ----    Date    ---- +  -- Status --\n")
	for _, item := range resource.Collection.Items {
		for _, data := range item.Data {
			if data.Name != "action" {
				continue
			}
			a, err := client.ValueToAction(data.Value)
			if err != nil {
				panic(err)
			}
			name := a.Name
			if len(name) < 30 {
				for i := len(name); i < 30; i++ {
					name += " "
				}
			}
			if len(name) > 30 {
				name = name[0:27] + "..."
			}
			target := a.Target
			if len(target) < 30 {
				for i := len(target); i < 30; i++ {
					target += " "
				}
			}
			if len(target) > 30 {
				target = target[0:27] + "..."
			}
			fmt.Printf("%.0f     %s   %s   %s    %s\n", a.ID, name, target,
				a.StartTime.Format(time.RFC3339), a.Status)
		}
	}
	return
}
开发者ID:Novemburr,项目名称:mig,代码行数:45,代码来源:investigator.go

示例3: searchCommands

func searchCommands(aid float64, show string, cli client.Client) (cmds []mig.Command, err error) {
	defer func() {
		fmt.Printf("\n")
		if e := recover(); e != nil {
			err = fmt.Errorf("searchCommands() -> %v", e)
		}
	}()
	base := fmt.Sprintf("search?type=command&actionid=%.0f", aid)
	switch show {
	case "found":
		base += "&foundanything=true"
	case "notfound":
		base += "&foundanything=false"
	}
	offset := 0
	// loop until all results have been retrieved using paginated queries
	for {
		fmt.Printf(".")
		target := fmt.Sprintf("%s&limit=50&offset=%d", base, offset)
		resource, err := cli.GetAPIResource(target)
		// because we query using pagination, the last query will return a 404 with no result.
		// When that happens, GetAPIResource returns an error which we do not report to the user
		if resource.Collection.Error.Message == "no results found" {
			err = nil
			break
		} else if err != nil {
			panic(err)
		}
		for _, item := range resource.Collection.Items {
			for _, data := range item.Data {
				if data.Name != "command" {
					continue
				}
				cmd, err := client.ValueToCommand(data.Value)
				if err != nil {
					panic(err)
				}
				cmds = append(cmds, cmd)
			}
		}
		// else increase limit and offset and continue
		offset += 50
	}
	return
}
开发者ID:rayyang2000,项目名称:mig,代码行数:45,代码来源:action_reader.go

示例4: searchFoundAnything

func searchFoundAnything(a mig.Action, wantFound bool, cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("searchFoundAnything() -> %v", e)
		}
	}()
	target := "search?type=command&limit=1000000&actionid=" + fmt.Sprintf("%.0f", a.ID)
	if wantFound {
		target += "&foundanything=true"
	} else {
		target += "&foundanything=false"
	}
	resource, err := cli.GetAPIResource(target)
	if err != nil {
		panic(err)
	}
	agents := make(map[float64]mig.Command)
	for _, item := range resource.Collection.Items {
		for _, data := range item.Data {
			if data.Name != "command" {
				continue
			}
			cmd, err := client.ValueToCommand(data.Value)
			if err != nil {
				panic(err)
			}
			agents[cmd.Agent.ID] = cmd
		}
	}
	if wantFound {
		fmt.Printf("%d agents have found things\n", len(agents))
	} else {
		fmt.Printf("%d agents have not found anything\n", len(agents))
	}
	if len(agents) > 0 {
		fmt.Println("---- Command ID ----    ---- Agent Name & ID----")
		for agtid, cmd := range agents {
			fmt.Printf("%20.0f    %s [%.0f]\n", cmd.ID, cmd.Agent.Name, agtid)
		}
	}
	return
}
开发者ID:Novemburr,项目名称:mig,代码行数:42,代码来源:action_reader.go

示例5: printStatus

func printStatus(cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("printStatus() -> %v", e)
		}
	}()
	st, err := cli.GetAPIResource("dashboard")
	if err != nil {
		panic(err)
	}
	var onlineagt, idleagt []string
	actout := make([]string, 2)
	actout[0] = "Latest Actions:"
	actout[1] = "----    ID      ---- + ----         Name         ---- + -Sent- + ----    Date     ---- + ---- Investigators ----"
	var onlineagents, onlineendpoints, idleagents, idleendpoints, newendpoints, doubleagents, disappearedendpoints, flappingendpoints float64
	for _, item := range st.Collection.Items {
		for _, data := range item.Data {
			switch data.Name {
			case "action":
				idstr, name, datestr, invs, sent, err := actionPrintShort(data.Value)
				if err != nil {
					panic(err)
				}
				str := fmt.Sprintf("%s   %s   %6d   %s   %s", idstr, name, sent, datestr, invs)
				actout = append(actout, str)
			case "online agents":
				onlineagents = data.Value.(float64)
			case "online endpoints":
				onlineendpoints = data.Value.(float64)
			case "idle agents":
				idleagents = data.Value.(float64)
			case "idle endpoints":
				idleendpoints = data.Value.(float64)
			case "new endpoints":
				newendpoints = data.Value.(float64)
			case "endpoints running 2 or more agents":
				doubleagents = data.Value.(float64)
			case "disappeared endpoints":
				disappearedendpoints = data.Value.(float64)
			case "flapping endpoints":
				flappingendpoints = data.Value.(float64)
			case "online agents by version":
				bData, err := json.Marshal(data.Value)
				if err != nil {
					panic(err)
				}
				var sum []mig.AgentsVersionsSum
				err = json.Unmarshal(bData, &sum)
				if err != nil {
					panic(err)
				}
				for _, asum := range sum {
					s := fmt.Sprintf("* version %s: %.0f agent", asum.Version, asum.Count)
					if asum.Count > 1 {
						s += "s"
					}
					onlineagt = append(onlineagt, s)
				}
			case "idle agents by version":
				bData, err := json.Marshal(data.Value)
				if err != nil {
					panic(err)
				}
				var sum []mig.AgentsVersionsSum
				err = json.Unmarshal(bData, &sum)
				if err != nil {
					panic(err)
				}
				for _, asum := range sum {
					s := fmt.Sprintf("* version %s: %.0f agent", asum.Version, asum.Count)
					if asum.Count > 1 {
						s += "s"
					}
					idleagt = append(idleagt, s)
				}
			}
		}
	}
	fmt.Println("\x1b[31;1m+------\x1b[0m")
	fmt.Printf("\x1b[31;1m| Agents & Endpoints summary:\n"+
		"\x1b[31;1m|\x1b[0m * %.0f online agents on %.0f endpoints\n"+
		"\x1b[31;1m|\x1b[0m * %.0f idle agents on %.0f endpoints\n"+
		"\x1b[31;1m|\x1b[0m * %.0f endpoints are running 2 or more agents\n"+
		"\x1b[31;1m|\x1b[0m * %.0f endpoints appeared over the last 7 days\n"+
		"\x1b[31;1m|\x1b[0m * %.0f endpoints disappeared over the last 7 days\n"+
		"\x1b[31;1m|\x1b[0m * %.0f endpoints have been flapping\n",
		onlineagents, onlineendpoints, idleagents, idleendpoints, doubleagents, newendpoints,
		disappearedendpoints, flappingendpoints)
	fmt.Println("\x1b[31;1m| Online agents by version:\x1b[0m")
	for _, s := range onlineagt {
		fmt.Println("\x1b[31;1m|\x1b[0m " + s)
	}
	fmt.Println("\x1b[31;1m| Idle agents by version:\x1b[0m")
	for _, s := range idleagt {
		fmt.Println("\x1b[31;1m|\x1b[0m " + s)
	}
	fmt.Println("\x1b[31;1m|\x1b[0m")
	for _, s := range actout {
		fmt.Println("\x1b[31;1m|\x1b[0m " + s)
		if len(actout) < 2 {
//.........这里部分代码省略.........
开发者ID:Novemburr,项目名称:mig,代码行数:101,代码来源:console.go

示例6: investigatorReader

// investigatorReader retrieves an agent from the api
// and enters prompt mode to analyze it
func investigatorReader(input string, cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("investigatorReader() -> %v", e)
		}
	}()
	inputArr := strings.Split(input, " ")
	if len(inputArr) < 2 {
		panic("wrong order format. must be 'investigator <investigatorid>'")
	}
	iid, err := strconv.ParseFloat(inputArr[1], 64)
	if err != nil {
		panic(err)
	}
	inv, err := cli.GetInvestigator(iid)
	if err != nil {
		panic(err)
	}

	fmt.Println("Entering investigator 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("Investigator %.0f named '%s'\n", inv.ID, inv.Name)
	prompt := fmt.Sprintf("\x1b[35;1minv %.0f>\x1b[0m ", iid)
	for {
		// completion
		var symbols = []string{"details", "exit", "help", "pubkey", "r", "lastactions"}
		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(input, " ")
		switch orders[0] {
		case "details":
			fmt.Printf("Investigator ID %.0f\nname     %s\nstatus   %s\nkey id   %s\ncreated  %s\nmodified %s\n",
				inv.ID, inv.Name, inv.Status, inv.PGPFingerprint, inv.CreatedAt, inv.LastModified)
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "help":
			fmt.Printf(`The following orders are available:
details			print the details of the investigator
exit			exit this mode
help			show this help
lastactions <limit>	print the last actions ran by the investigator. limit=10 by default.
pubkey			show the armored public key of the investigator
r			refresh the investigator (get latest version from upstream)
setstatus <status>	changes the status of the investigator to <status> (can be 'active' or 'disabled')
`)
		case "lastactions":
			limit := 10
			if len(orders) > 1 {
				limit, err = strconv.Atoi(orders[1])
				if err != nil {
					panic(err)
				}
			}
			err = printInvestigatorLastActions(iid, limit, cli)
			if err != nil {
				panic(err)
			}
		case "pubkey":
			armoredPubKey, err := pgp.ArmorPubKey(inv.PublicKey)
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s\n", armoredPubKey)
		case "r":
			inv, err = cli.GetInvestigator(iid)
			if err != nil {
				panic(err)
			}
			fmt.Println("Reload succeeded")
		case "setstatus":
			if len(orders) != 2 {
				fmt.Println("error: must be 'setstatus <status>'. try 'help'")
				break
			}
			newstatus := orders[1]
			err = cli.PostInvestigatorStatus(iid, newstatus)
			if err != nil {
				panic(err)
			} else {
				fmt.Println("Investigator status set to", newstatus)
			}
		case "":
//.........这里部分代码省略.........
开发者ID:Novemburr,项目名称:mig,代码行数:101,代码来源:investigator.go

示例7: investigatorCreator

// investigatorCreator prompt the user for a name and the path to an armored
// public key and calls the API to create a new investigator
func investigatorCreator(cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("investigatorCreator() -> %v", e)
		}
	}()
	var (
		name   string
		pubkey []byte
	)
	fmt.Println("Entering investigator creation mode. Please provide the full name\n" +
		"and the public key of the new investigator.")
	name, err = readline.String("name> ")
	if err != nil {
		panic(err)
	}
	if len(name) < 3 {
		panic("input name too short")
	}
	fmt.Printf("Name: '%s'\n", name)
	fmt.Println("Please provide a public key. You can either provide a local path to the\n" +
		"armored public key file, or a full length PGP fingerprint.\n" +
		"example:\npubkey> 0x716CFA6BA8EBB21E860AE231645090E64367737B")
	input, err := readline.String("pubkey> ")
	if err != nil {
		panic(err)
	}
	re := regexp.MustCompile(`^0x[ABCDEF0-9]{8,64}$`)
	if re.MatchString(input) {
		var keyserver string
		if cli.Conf.GPG.Keyserver == "" {
			keyserver = "http://gpg.mozilla.org"
		}
		fmt.Println("retrieving public key from", keyserver)
		pubkey, err = pgp.GetArmoredKeyFromKeyServer(input, keyserver)
		if err != nil {
			panic(err)
		}
	} else {
		fmt.Println("retrieving public key from", input)
		pubkey, err = ioutil.ReadFile(input)
		if err != nil {
			panic(err)
		}
	}
	fmt.Printf("%s\n", pubkey)
	input, err = readline.String("create investigator? (y/n)> ")
	if err != nil {
		panic(err)
	}
	if input != "y" {
		fmt.Println("abort")
		return
	}
	inv, err := cli.PostInvestigator(name, pubkey)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Investigator '%s' successfully created with ID %.0f\n",
		inv.Name, inv.ID)
	return
}
开发者ID:Novemburr,项目名称:mig,代码行数:64,代码来源:investigator.go

示例8: 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

示例9: followAction

func followAction(a mig.Action, cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("followAction() -> %v", e)
		}
	}()
	fmt.Printf("Entering follower mode for action ID %.0f\n", a.ID)
	sent := 0
	dotter := 0
	previousctr := 0
	status := ""
	attempts := 0
	var completion float64
	for {
		a, _, err = cli.GetAction(a.ID)
		if err != nil {
			attempts++
			time.Sleep(1 * time.Second)
			if attempts >= 30 {
				panic("failed to retrieve action after 30 seconds. launch may have failed")
			}
			continue
		}
		if status == "" {
			status = a.Status
		}
		if status != a.Status {
			fmt.Printf("action status is now '%s'\n", a.Status)
			status = a.Status
		}
		// exit follower mode if status isn't one we follow,
		// or enough commands have returned
		// or expiration time has passed
		if (status != "init" && status != "preparing" && status != "inflight") ||
			(a.Counters.Done > 0 && a.Counters.Done >= a.Counters.Sent) ||
			(time.Now().After(a.ExpireAfter)) {
			goto finish
			break
		}
		// init counters
		if sent == 0 {
			if a.Counters.Sent == 0 {
				time.Sleep(1 * time.Second)
				continue
			} else {
				sent = a.Counters.Sent
				fmt.Printf("%d commands have been sent\n", sent)
			}
		}
		if a.Counters.Done > 0 && a.Counters.Done > previousctr {
			completion = (float64(a.Counters.Done) / float64(a.Counters.Sent)) * 100
			if completion > 99.9 && a.Counters.Done != a.Counters.Sent {
				completion = 99.9
			}
			previousctr = a.Counters.Done
		}
		time.Sleep(1 * time.Second)
		dotter++
		if dotter >= 5 {
			fmt.Printf("%.1f%% done - %d/%d - %s\n",
				completion, a.Counters.Done, a.Counters.Sent,
				time.Now().Sub(a.StartTime).String())
			dotter = 0
		}
	}
finish:
	fmt.Printf("leaving follower mode after %s\n", a.LastUpdateTime.Sub(a.StartTime).String())
	fmt.Printf("%d sent, %d done: %d returned, %d cancelled, %d expired, %d failed, %d timed out, %d still in flight\n",
		a.Counters.Sent, a.Counters.Done, a.Counters.Done, a.Counters.Cancelled, a.Counters.Expired,
		a.Counters.Failed, a.Counters.TimeOut, a.Counters.InFlight)
	return
}
开发者ID:rayyang2000,项目名称:mig,代码行数:72,代码来源:action_launcher.go

示例10: 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, cli client.Client) (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")
	} 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
		fmt.Printf("Entering action launcher using template '%s'\n", a.Name)
	}
	hasTimes := false
	hasSignatures := false
	hasEvaluatedTarget := 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", "listagents", "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 := modules.Available[operation.Module]; ok {
				// instanciate and call module parameters creation function
				run := modules.Available[operation.Module].NewRun()
				if _, ok := run.(modules.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 = run.(modules.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",
				a.ID, a.Name, a.Target, a.Description.Author, a.Description.Email,
				a.Description.Revision, a.Description.URL,
//.........这里部分代码省略.........
开发者ID:rayyang2000,项目名称:mig,代码行数:101,代码来源:action_launcher.go

示例11: 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

示例12: main

func main() {
	var (
		conf                                           client.Configuration
		cli                                            client.Client
		err                                            error
		op                                             mig.Operation
		a                                              mig.Action
		migrc, show, render, target, expiration, afile string
		modargs                                        []string
		modRunner                                      interface{}
	)
	defer func() {
		if e := recover(); e != nil {
			fmt.Fprintf(os.Stderr, "%v\n", e)
		}
	}()
	homedir := client.FindHomedir()
	fs := flag.NewFlagSet("mig flag", flag.ContinueOnError)
	fs.Usage = continueOnFlagError
	fs.StringVar(&migrc, "c", homedir+"/.migrc", "alternative configuration file")
	fs.StringVar(&show, "show", "found", "type of results to show")
	fs.StringVar(&render, "render", "text", "results rendering mode")
	fs.StringVar(&target, "t", fmt.Sprintf("status='%s' AND mode='daemon'", mig.AgtStatusOnline), "action target")
	fs.StringVar(&expiration, "e", "300s", "expiration")
	fs.StringVar(&afile, "i", "/path/to/file", "Load action from file")

	// if first argument is missing, or is help, print help
	// otherwise, pass the remainder of the arguments to the module for parsing
	// this client is agnostic to module parameters
	if len(os.Args) < 2 || os.Args[1] == "help" || os.Args[1] == "-h" || os.Args[1] == "--help" {
		usage()
	}

	if len(os.Args) < 2 || os.Args[1] == "-V" {
		fmt.Println(version)
		os.Exit(0)
	}

	// when reading the action from a file, go directly to launch
	if os.Args[1] == "-i" {
		err = fs.Parse(os.Args[1:])
		if err != nil {
			panic(err)
		}
		if afile == "/path/to/file" {
			panic("-i flag must take an action file path as argument")
		}
		a, err = mig.ActionFromFile(afile)
		if err != nil {
			panic(err)
		}
		fmt.Fprintf(os.Stderr, "[info] launching action from file, all flags are ignored\n")
		goto readytolaunch
	}

	// arguments parsing works as follow:
	// * os.Args[1] must contain the name of the module to launch. we first verify
	//   that a module exist for this name and then continue parsing
	// * os.Args[2:] contains both global options and module parameters. We parse the
	//   whole []string to extract global options, and module parameters will be left
	//   unparsed in fs.Args()
	// * fs.Args() with the module parameters is passed as a string to the module parser
	//   which will return a module operation to store in the action
	op.Module = os.Args[1]
	if _, ok := modules.Available[op.Module]; !ok {
		panic("Unknown module " + op.Module)
	}

	// -- Ugly hack Warning --
	// Parse() will fail on the first flag that is not defined, but in our case module flags
	// are defined in the module packages and not in this program. Therefore, the flag parse error
	// is expected. Unfortunately, Parse() writes directly to stderr and displays the error to
	// the user, which confuses them. The right fix would be to prevent Parse() from writing to
	// stderr, since that's really the job of the calling program, but in the meantime we work around
	// it by redirecting stderr to null before calling Parse(), and put it back to normal afterward.
	// for ref, issue is at https://github.com/golang/go/blob/master/src/flag/flag.go#L793
	fs.SetOutput(os.NewFile(uintptr(87592), os.DevNull))
	err = fs.Parse(os.Args[2:])
	fs.SetOutput(nil)
	if err != nil {
		// ignore the flag not defined error, which is expected because
		// module parameters are defined in modules and not in main
		if len(err.Error()) > 30 && err.Error()[0:29] == "flag provided but not defined" {
			// requeue the parameter that failed
			modargs = append(modargs, err.Error()[31:])
		} else {
			// if it's another error, panic
			panic(err)
		}
	}
	for _, arg := range fs.Args() {
		modargs = append(modargs, arg)
	}
	modRunner = modules.Available[op.Module].Runner()
	if _, ok := modRunner.(modules.HasParamsParser); !ok {
		fmt.Fprintf(os.Stderr, "[error] module '%s' does not support command line invocation\n", op.Module)
		os.Exit(2)
	}
	op.Parameters, err = modRunner.(modules.HasParamsParser).ParamsParser(modargs)
	if err != nil || op.Parameters == nil {
//.........这里部分代码省略.........
开发者ID:Novemburr,项目名称:mig,代码行数:101,代码来源:main.go


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