Updating the Port Scanning Functionality
Let's update the port scanning functionality now.
We'll cover the following...
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:
import ("fmt""io""os""github.com/spf13/cobra""pragprog.com/rggo/cobra/pScan/scan")
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:
func init() {rootCmd.AddCommand(scanCmd)scanCmd.Flags().IntSliceP("ports", "p", []int{22, 80, 443}, "ports to scan")}
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:
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
...