如何写一个脚本检查网络安全

wen 实用脚本 3

本文目录导读:

如何写一个脚本检查网络安全

  1. 基础网络安全检查脚本
  2. Python网络安全检查脚本
  3. 使用现成的安全工具
  4. 自动化安全检查脚本
  5. 使用说明
  6. 注意事项

我来为您详细介绍如何编写网络安全检查脚本,从基础到进阶。

基础网络安全检查脚本

简单的端口扫描脚本(Bash)

#!/bin/bash
# 基础端口扫描器
TARGET=$1
PORTS=(22 80 443 3306 8080 8443)
echo "开始扫描 $TARGET ..."
for PORT in "${PORTS[@]}"; do
    timeout 1 bash -c "echo >/dev/tcp/$TARGET/$PORT" 2>/dev/null && \
    echo "端口 $PORT 开放" || \
    echo "端口 $PORT 关闭"
done
echo "扫描完成!"

Python网络安全检查脚本

完整的网络扫描器

#!/usr/bin/env python3
"""
网络安全检查脚本
功能:端口扫描、服务检测、安全漏洞检查
"""
import socket
import ssl
import sys
import time
from concurrent.futures import ThreadPoolExecutor
class SecurityScanner:
    def __init__(self, target, timeout=3):
        self.target = target
        self.timeout = timeout
        self.open_ports = []
    def scan_port(self, port):
        """扫描单个端口"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(self.timeout)
            result = sock.connect_ex((self.target, port))
            if result == 0:
                service = self.get_service_name(port)
                self.open_ports.append((port, service))
                print(f"[+] 端口 {port} ({service}) 开放")
            sock.close()
        except:
            pass
    def get_service_name(self, port):
        """获取端口对应的服务名称"""
        common_services = {
            21: "FTP", 22: "SSH", 23: "Telnet",
            25: "SMTP", 53: "DNS", 80: "HTTP",
            443: "HTTPS", 3306: "MySQL", 3389: "RDP",
            5432: "PostgreSQL", 6379: "Redis", 8080: "HTTP-Proxy"
        }
        return common_services.get(port, "Unknown")
    def scan_common_ports(self):
        """扫描常见端口"""
        common_ports = [21, 22, 23, 25, 53, 80, 110, 143, 443, 
                       993, 995, 3306, 3389, 5432, 6379, 8080, 8443]
        print(f"\n[*] 开始扫描 {self.target}...")
        with ThreadPoolExecutor(max_workers=50) as executor:
            executor.map(self.scan_port, common_ports)
        return self.open_ports
    def check_ssl_certificate(self):
        """检查SSL证书"""
        if 443 in [port for port, _ in self.open_ports]:
            try:
                context = ssl.create_default_context()
                with socket.create_connection((self.target, 443), timeout=self.timeout) as sock:
                    with context.wrap_socket(sock, server_hostname=self.target) as ssock:
                        cert = ssock.getpeercert()
                        print(f"\n[SSL] 证书信息:")
                        print(f"  主题: {cert.get('subject')}")
                        print(f"  颁发者: {cert.get('issuer')}")
                        print(f"  有效期: {cert.get('notBefore')} - {cert.get('notAfter')}")
                        # 检查证书有效性
                        try:
                            ssl.match_hostname(cert, self.target)
                            print("[+] SSL证书验证通过")
                        except ssl.CertificateError as e:
                            print(f"[-] SSL证书问题: {e}")
            except Exception as e:
                print(f"[-] SSL证书检查失败: {e}")
    def check_vulnerabilities(self):
        """检查常见漏洞(简化版)"""
        print("\n[*] 开始漏洞检查...")
        # 检查常见安全配置
        tests = [
            ("HTTP headers", self._check_http_headers),
            ("SSH version", self._check_ssh_version),
            ("Default credentials", self._check_default_creds)
        ]
        for test_name, test_func in tests:
            try:
                test_func()
            except Exception as e:
                print(f"[-] {test_name}检查失败: {e}")
    def _check_http_headers(self):
        """检查HTTP安全头"""
        if 80 in [port for port, _ in self.open_ports]:
            import http.client
            conn = http.client.HTTPConnection(self.target, timeout=self.timeout)
            conn.request("GET", "/")
            response = conn.getresponse()
            headers = dict(response.getheaders())
            security_headers = {
                "X-Frame-Options": "防止点击劫持",
                "X-Content-Type-Options": "防止MIME类型嗅探",
                "X-XSS-Protection": "XSS保护",
                "Content-Security-Policy": "内容安全策略",
                "Strict-Transport-Security": "HSTS"
            }
            print(f"\n[HTTP] 安全头检查:")
            for header, description in security_headers.items():
                if header in headers:
                    print(f"  [+] {header}: {headers[header]}")
                else:
                    print(f"  [-] 缺少 {header} ({description})")
    def _check_ssh_version(self):
        """检查SSH版本"""
        if 22 in [port for port, _ in self.open_ports]:
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(self.timeout)
                sock.connect((self.target, 22))
                banner = sock.recv(1024).decode().strip()
                print(f"\n[SSH] 版本信息: {banner}")
                # 检查是否有已知漏洞
                weak_versions = ["SSH-1.", "OpenSSH_2.", "OpenSSH_3.", "OpenSSH_4."]
                for weak in weak_versions:
                    if weak in banner:
                        print(f"  [-] 警告: 发现可能存在漏洞的SSH版本!")
                sock.close()
            except:
                pass
    def _check_default_creds(self):
        """检查常见默认凭据"""
        print("\n[默认凭据] 检查常见默认配置...")
        # 这里是一个示例,实际使用时需要谨慎
        # 建议集成如Hydra等工具的检查
        pass
    def generate_report(self):
        """生成安全检查报告"""
        print("\n" + "="*50)
        print("网络安全检查报告")
        print("="*50)
        print(f"目标: {self.target}")
        print(f"检查时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"发现开放端口: {len(self.open_ports)}")
        if self.open_ports:
            print("\n开放端口列表:")
            for port, service in self.open_ports:
                print(f"  - {port}/{service}")
        print("\n" + "="*50)
def main():
    if len(sys.argv) != 2:
        print("用法: python3 scanner.py <目标IP或域名>")
        sys.exit(1)
    target = sys.argv[1]
    scanner = SecurityScanner(target)
    # 执行扫描
    scanner.scan_common_ports()
    scanner.check_ssl_certificate()
    scanner.check_vulnerabilities()
    scanner.generate_report()
if __name__ == "__main__":
    main()

使用现成的安全工具

集成Nmap的脚本

#!/usr/bin/env python3
"""
使用Nmap进行安全检查
需要先安装: pip install python-nmap
"""
import nmap
import json
class NmapSecurityScanner:
    def __init__(self, target):
        self.target = target
        self.nm = nmap.PortScanner()
    def scan_network(self):
        """扫描网络"""
        print(f"[*] 正在扫描 {self.target}...")
        # 执行Nmap扫描
        self.nm.scan(self.target, arguments='-sV -sC -O')
        results = {}
        for host in self.nm.all_hosts():
            results[host] = {
                'hostname': self.nm[host].hostname(),
                'state': self.nm[host].state(),
                'protocols': {}
            }
            for proto in self.nm[host].all_protocols():
                ports = self.nm[host][proto].keys()
                results[host]['protocols'][proto] = {}
                for port in ports:
                    service_info = self.nm[host][proto][port]
                    results[host]['protocols'][proto][port] = {
                        'state': service_info['state'],
                        'name': service_info['name'],
                        'product': service_info.get('product', ''),
                        'version': service_info.get('version', '')
                    }
                    print(f"  端口 {port}/{proto}: {service_info['state']} - {service_info['name']} {service_info.get('version', '')}")
        return results
    def export_report(self, filename='scan_result.json'):
        """导出扫描报告"""
        results = self.scan_network()
        with open(filename, 'w') as f:
            json.dump(results, f, indent=2)
        print(f"\n[+] 报告已保存到 {filename}")
# 使用示例
if __name__ == "__main__":
    scanner = NmapSecurityScanner("192.168.1.1")
    scanner.export_report()

自动化安全检查脚本

#!/usr/bin/env python3
"""
自动化网络安全检查脚本
包含:扫描、分析、报告生成
"""
import subprocess
import json
import datetime
import os
from typing import Dict, List, Any
class AutomatedSecurityAudit:
    def __init__(self, target: str, output_dir: str = "./security_reports"):
        self.target = target
        self.output_dir = output_dir
        self.timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        # 创建输出目录
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
    def run_command(self, command: str) -> str:
        """执行系统命令"""
        try:
            result = subprocess.run(command.split(), capture_output=True, text=True, timeout=300)
            return result.stdout
        except subprocess.TimeoutExpired:
            return f"命令执行超时: {command}"
        except Exception as e:
            return f"执行错误: {e}"
    def check_system_info(self) -> Dict[str, Any]:
        """检查系统信息"""
        info = {}
        # 检查系统信息
        info['hostname'] = self.run_command("hostname").strip()
        info['os_info'] = self.run_command("uname -a").strip()
        info['cpu_info'] = self.run_command("cat /proc/cpuinfo | grep 'model name' | head -1").strip()
        info['memory_info'] = self.run_command("free -h").strip()
        info['disk_info'] = self.run_command("df -h").strip()
        # 检查网络配置
        info['ip_address'] = self.run_command("hostname -I").strip()
        info['network_interfaces'] = self.run_command("ip addr show").strip()
        info['routing_table'] = self.run_command("route -n").strip()
        return info
    def check_network_security(self) -> Dict[str, Any]:
        """检查网络安全配置"""
        security_checks = {}
        # 检查防火墙
        security_checks['firewall'] = {
            'ufw_status': self.run_command("sudo ufw status"),
            'iptables_rules': self.run_command("sudo iptables -L -n"),
            'ip6tables_rules': self.run_command("sudo ip6tables -L -n")
        }
        # 检查开放端口
        security_checks['open_ports'] = self.run_command("netstat -tulpn")
        # 检查网络服务
        security_checks['running_services'] = self.run_command("systemctl list-units --type=service --state=running")
        # 检查SSH配置
        security_checks['ssh_config'] = {
            'sshd_config': self.run_command("cat /etc/ssh/sshd_config"),
            'ssh_host_keys': self.run_command("ls -la /etc/ssh/")
        }
        return security_checks
    def check_user_security(self) -> Dict[str, Any]:
        """检查用户安全"""
        user_checks = {}
        # 检查用户账户
        user_checks['users'] = self.run_command("cat /etc/passwd")
        user_checks['sudo_users'] = self.run_command("getent group sudo")
        user_checks['last_logins'] = self.run_command("last -10")
        # 检查密码策略
        user_checks['password_policy'] = self.run_command("cat /etc/login.defs | grep -E 'PASS_MAX_DAYS|PASS_MIN_DAYS|PASS_MIN_LEN|PASS_WARN_AGE'")
        # 检查SSH密钥
        user_checks['authorized_keys'] = {}
        for user in os.listdir('/home/'):
            key_path = f"/home/{user}/.ssh/authorized_keys"
            if os.path.exists(key_path):
                user_checks['authorized_keys'][user] = self.run_command(f"cat {key_path}")
        return user_checks
    def check_file_permissions(self) -> Dict[str, Any]:
        """检查文件权限"""
        permission_checks = {}
        # 检查敏感文件权限
        sensitive_files = [
            "/etc/shadow", "/etc/passwd", "/etc/sudoers",
            "/etc/ssh/sshd_config", "/etc/crontab"
        ]
        for file_path in sensitive_files:
            if os.path.exists(file_path):
                permission_checks[file_path] = self.run_command(f"ls -la {file_path}")
        # 检查SUID文件
        permission_checks['suid_files'] = self.run_command("find / -perm -4000 -type f 2>/dev/null")
        # 检查SGID文件
        permission_checks['sgid_files'] = self.run_command("find / -perm -2000 -type f 2>/dev/null")
        return permission_checks
    def check_security_updates(self) -> Dict[str, Any]:
        """检查安全更新"""
        update_checks = {}
        # 检查系统更新
        update_checks['available_updates'] = self.run_command("apt list --upgradable 2>/dev/null | grep -i security")
        # 检查已安装的安全更新
        update_checks['installed_updates'] = self.run_command("apt list --installed 2>/dev/null | grep -i security")
        # 检查自动更新配置
        update_checks['auto_updates'] = self.run_command("cat /etc/apt/apt.conf.d/20auto-upgrades 2>/dev/null")
        return update_checks
    def generate_audit_report(self) -> str:
        """生成审计报告"""
        report = f"""
========================================
        网络安全审计报告
========================================
审计时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
目标系统: {self.target}
一、系统信息
{json.dumps(self.check_system_info(), indent=2)}
二、网络安全配置
{json.dumps(self.check_network_security(), indent=2)}
三、用户安全
{json.dumps(self.check_user_security(), indent=2)}
四、文件权限
{json.dumps(self.check_file_permissions(), indent=2)}
五、安全更新
{json.dumps(self.check_security_updates(), indent=2)}
六、安全建议
根据检查结果,建议:
1. 及时应用系统安全更新
2. 检查并关闭不必要的端口
3. 审查用户权限和SSH配置
4. 确保敏感文件权限正确
5. 配置防火墙规则
6. 启用日志审计
========================================
报告生成完毕
        """
        # 保存报告
        report_file = f"{self.output_dir}/security_audit_{self.timestamp}.txt"
        with open(report_file, 'w') as f:
            f.write(report)
        return report_file
    def run_full_audit(self):
        """运行完整审计"""
        print("[*] 开始网络安全审计...")
        print(f"[*] 目标: {self.target}")
        print("[*] 正在收集系统信息...")
        self.check_system_info()
        print("[*] 正在检查网络安全配置...")
        self.check_network_security()
        print("[*] 正在检查用户安全...")
        self.check_user_security()
        print("[*] 正在检查文件权限...")
        self.check_file_permissions()
        print("[*] 正在检查安全更新...")
        self.check_security_updates()
        print("[*] 正在生成报告...")
        report_path = self.generate_audit_report()
        print(f"[+] 审计完成!报告已保存到: {report_path}")
if __name__ == "__main__":
    # 使用示例
    auditor = AutomatedSecurityAudit("localhost")
    auditor.run_full_audit()

使用说明

安装依赖

# Python依赖
pip install python-nmap
# 系统工具
sudo apt-get install nmap net-tools
# 如果使用Linux,确保有权限执行
chmod +x security_scanner.py

运行脚本

# 运行基础扫描器
python3 security_scanner.py 192.168.1.1
# 运行完整审计脚本
python3 automated_audit.py
# 使用Nmap扫描器
python3 nmap_scanner.py

注意事项

  1. 合法性:只扫描自己拥有的系统或获得授权的系统
  2. 权限:某些检查需要root权限
  3. 性能:大规模扫描可能影响网络性能
  4. 更新:定期更新漏洞库和检测规则
  5. 日志:记录所有扫描活动

这些脚本提供了基础的网络安全检查功能,可以根据实际需求进行扩展和定制。

抱歉,评论功能暂时关闭!