nmap.go
1 // Copyright (c) 2024-2026 Tencent Zhuque Lab. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // Requirement: Any integration or derivative work must explicitly attribute 16 // Tencent Zhuque Lab (https://github.com/Tencent/AI-Infra-Guard) in its 17 // documentation or user interface, as detailed in the NOTICE file. 18 19 package utils 20 21 import ( 22 "encoding/xml" 23 "fmt" 24 "os/exec" 25 ) 26 27 // 定义XML解析结构体 28 type NmapRun struct { 29 Hosts []Host `xml:"host"` 30 } 31 type Address struct { 32 Addr string `xml:"addr,attr"` 33 AddrType string `xml:"addrtype,attr"` 34 } 35 36 type Host struct { 37 Ports Ports `xml:"ports"` 38 Address Address `xml:"address"` 39 } 40 41 type Ports struct { 42 PortList []Port `xml:"port"` 43 } 44 45 type Port struct { 46 Protocol string `xml:"protocol,attr"` 47 PortID int `xml:"portid,attr"` 48 State State `xml:"state"` 49 } 50 51 type State struct { 52 State string `xml:"state,attr"` 53 } 54 55 func NmapScan(target string, port string) (*NmapRun, error) { 56 // 检测nmap是否可用 57 _, err := exec.LookPath("nmap") 58 if err != nil { 59 return nil, fmt.Errorf("nmap不可用: %v", err) 60 } 61 // 执行nmap扫描(快速模式,无服务识别) 62 cmd := exec.Command("nmap", "-T4", "-p", port, target, "-oX", "-") 63 output, err := cmd.CombinedOutput() 64 if err != nil { 65 return nil, fmt.Errorf("nmap扫描失败: %v\n输出: %s", err, string(output)) 66 } 67 // 解析XML结果 68 var result NmapRun 69 if err := xml.Unmarshal(output, &result); err != nil { 70 return nil, fmt.Errorf("解析nmap结果失败: %v", err) 71 } 72 return &result, nil 73 }