Search⌘ K

Updating the Port Scanning Functionality

Explore updating port scanning functionality in a Go CLI app built with the Cobra framework. Learn how to add command-line flags for specifying ports, implement scan actions, handle outputs with io.Writer, and create tests to validate the scanning process. This lesson guides you through modifying command files, managing hosts and ports input, and improving CLI tool flexibility.

Updating the cmd/scan.go file

We edit the import section and add the io package to use the io.Writer interface, the os package to use the os.Stdout, and our scan package for the port scan functionality:

Go (1.6.2)
import (
"fmt"
"io"
"os"
"github.com/spf13/cobra"
"pragprog.com/rggo/cobra/pScan/scan"
)
Updating the import section

Then we edit the init() function to include a local flag --ports or -p to allow the user to specify a slice of ports to be scanned. We use the method Flags() of the type scanCmd to create a flag that is available only for this command:

Go (1.6.2)
func init() {
rootCmd.AddCommand(scanCmd)
scanCmd.Flags().IntSliceP("ports", "p", []int{22, 80, 443}, "ports to scan")
}
Updating the init() function

In this function, we’re using the method IntSliceP() to create a flag that takes a slice of integer numbers. By default, this flag sets the ports to be scanned as 22, 80, and 443.

Now, we edit the scanCmd type definition according to the command requirements. We update the short description to “Run a port scan on the hosts” and remove the long description:

Go (1.6.2)
var scanCmd = &cobra.Command{
Use: "scan",
Short: "Run a port scan on the hosts",

We implement the action by replacing the Run property with RunE, as we did when we implemented the hosts commands. This function handles both the hostsfile and ports ...