端口扫描(go)
Posted dopenser
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了端口扫描(go)相关的知识,希望对你有一定的参考价值。
golang学习
通过golang打造高效的端口扫描器
golang源码如下
package main import ( "flag" "fmt" "net" "os" "regexp" "strconv" "strings" "sync" ) var port string var portRange string var parallelCounts int func init() { flag.StringVar(&port, "p", "21,22,23,53,80,135,139,443,445,1080,1433,1521,2222,3000,3306,3389,8080,8888,50050,55553","port") flag.StringVar(&portRange, "r", "", "range ports. format is <from>-<to>. eg. 100-200") flag.IntVar(¶llelCounts, "s", 100, "speed") flag.Usage = func() { fmt.Fprintf(os.Stderr, "\\nUsage: [Options] <IP>\\n\\neg: ./portscan -r 1-65535 -s 10000 127.0.0.1\\n\\nOptions:\\n\\n") flag.PrintDefaults() } flag.Parse() } func printOpeningPort(port int) { fmt.Println("port " + strconv.Itoa(port) + " is opening") } func checkPort(ip net.IP, port int, wg *sync.WaitGroup, parallelChan *chan int) { defer wg.Done() tcpAddr := net.TCPAddr{ IP: ip, Port: port, } conn, err := net.DialTCP("tcp", nil, &tcpAddr) if err == nil { printOpeningPort(port) conn.Close() } else{ //fmt.Println("port " + strconv.Itoa(port) + " is close") } <-*parallelChan } func main() { args := flag.Args() if len(args) != 1 { flag.Usage() } else { ip := net.ParseIP(flag.Arg(0)) wg := sync.WaitGroup{} if portRange != "" { matched, _ := regexp.Match(`^\\d+-\\d+$`, []byte(portRange)) if !matched { flag.Usage() } else { portSecs := strings.Split(portRange, "-") startPort, err1 := strconv.Atoi(portSecs[0]) endPort, err2 := strconv.Atoi(portSecs[1]) if err1 != nil || err2 != nil || startPort < 1 || endPort < 2 || endPort <= startPort || parallelCounts < 1 { flag.Usage() } else { wg.Add(endPort - startPort + 1) parallelChan := make(chan int, parallelCounts) for i := startPort; i <= endPort; i++ { parallelChan <- 1 go checkPort(ip, i, &wg, ¶llelChan) } wg.Wait() } } } else { parallelChan := make(chan int, parallelCounts) arr:=strings.Split(port,",") wg.Add(len(arr)) for i :=0 ; i < len(arr); i++ { p,err:=strconv.Atoi(arr[i]) if err == nil { parallelChan <- 1 go checkPort(ip, p, &wg, ¶llelChan) } } wg.Wait() } } }
打包可执行文件
windows:go build portscan.go
linux:
set GOARCH=amd64
set GOOS=linux
go build portscan.go
压缩:go build -ldflags "-s -w" portscan.go
效果如下
以上是关于端口扫描(go)的主要内容,如果未能解决你的问题,请参考以下文章
[Go] 通过 17 个简短代码片段,切底弄懂 channel 基础
解决go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘(代码片段