YJWANG

[Golang] Linux 포트 오픈 체크 본문

90.Programming

[Golang] Linux 포트 오픈 체크

왕영주 2021. 5. 3. 12:31

Golang으로 TCP 포트 오픈 체크하는 프로그램에 대해 포스팅 하겠습니다.
아래와 같이 코딩한 이후

package main

import (
    "fmt"
    "net"
    "time"
)

func main() {
    host := "localhost"
    port := "8888"
    address := net.JoinHostPort(host, port)
    conn, err := net.DialTimeout("tcp", address, 3*time.Second)
    if err != nil {
        fmt.Println(err)
    } else if conn != nil {
        defer conn.Close()
        fmt.Printf("%s:%s is opened \n", host, port)
    }
}

오픈된 포트를 스캔했을 때, 오픈되지 않을 포트를 스캔했을 때

## 오픈되지 않음
# go run test.go
dial tcp 127.0.0.1:8888: connect: connection refused

## 오픈 됨
# go run test.go
localhost:8888 is opened

cobra library를 이용하면 아래와 같이 만들 수도 있습니다.
참고 : https://yjwang.tistory.com/137

help

# go run main.go get open
Error: required flag(s) "host", "port" not set
Usage:
  yjwang-init get open [flags]

Flags:
  -h, --help          help for open
  -i, --host string   destination address for checking (required)
  -p, --port string   destination port for checking (required)

Error: required flag(s) "host", "port" not set
exit status 1

오픈 체크

# go run main.go get open -i 127.0.0.1 -p 8888
dial tcp 127.0.0.1:8888: connect: connection refused

# go run main.go get open -i 127.0.0.1 -p 8888
127.0.0.1:8888 is opened

Sample Code

/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
    "fmt"
    "net"
    "time"

    "github.com/spf13/cobra"
)

var (
    host string
    port string
)

// openCmd represents the open command
var openCmd = &cobra.Command{
    Use:   "open",
    Short: "Check port is opend",
    Run: func(cmd *cobra.Command, args []string) {
        address := net.JoinHostPort(host, port)
        conn, err := net.DialTimeout("tcp", address, 3*time.Second)
        if err != nil {
            fmt.Println(err)
        } else if conn != nil {
            defer conn.Close()
            fmt.Printf("%s:%s is opened \n", host, port)
        }
    },
}

func init() {
    getCmd.AddCommand(openCmd)
    openCmd.Flags().StringVarP(&host, "host", "i", "", "destination address for checking (required)")
    openCmd.MarkFlagRequired("host")
    openCmd.Flags().StringVarP(&port, "port", "p", "", "destination port for checking (required)")
    openCmd.MarkFlagRequired("port")
    // Here you will define your flags and configuration settings.

    // Cobra supports Persistent Flags which will work for this command
    // and all subcommands, e.g.:
    // openCmd.PersistentFlags().String("foo", "", "A help for foo")

    // Cobra supports local flags which will only run when this command
    // is called directly, e.g.:
    // openCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
반응형