使用python实现端口连通性探测

背景

公司需要添加新的网段,所以需要对业务所有的机器进行端口探测,看是否需要放开iptables以及安全组,以下是脚本,大家修改后就可以使用

python 复制代码
from datetime import datetime
import socket
import logging
def log_format():
    # 输出到console
    ch_formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)  # 指定被处理的信息级别为最低级INFO,低于level级别的信息将被忽略
    ch.setFormatter(ch_formatter)
    # 输出到file
    formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
    fh = logging.FileHandler(filename="./output_%s.log" % (datetime.now().strftime('%Y%m%d')), mode='w',
                             encoding='utf-8')  # 不拆分日志文件,a指追加模式,w为覆盖模式
    fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logger.addHandler(ch)
    logger.addHandler(fh)
    return logger



def probe(ip, port=22, timeout=5):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(timeout)
    try:
        sock.connect((ip, port))
        return True
    except (socket.timeout, ConnectionRefusedError):
        return False
    finally:
        sock.close()

now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
result_file_name = f'/root/jarvisyqliu/result_{now}.txt'
log_format()
with open('/root/jarvisyqliu/ip.txt', 'r') as ip_file:
    for line in ip_file:
        ip = line.strip()
        logging.info(f'scaning...{ip}')
        with open(result_file_name, 'a') as result_file:
            if probe(ip):
                result_file.write(f'{ip} ok\n')
            else:
                result_file.write(f'{ip} error\n')
相关推荐
C嘎嘎嵌入式开发36 分钟前
(2)100天python从入门到拿捏
开发语言·python
Stanford_11061 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
white-persist3 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
Java 码农3 小时前
Centos7 maven 安装
java·python·centos·maven
倔强青铜三4 小时前
苦练Python第63天:零基础玩转TOML配置读写,tomllib模块实战
人工智能·python·面试
浔川python社4 小时前
《网络爬虫技术规范与应用指南系列》(xc—3):合规实操与场景落地
python
B站计算机毕业设计之家4 小时前
智慧交通项目:Python+YOLOv8 实时交通标志系统 深度学习实战(TT100K+PySide6 源码+文档)✅
人工智能·python·深度学习·yolo·计算机视觉·智慧交通·交通标志
IT森林里的程序猿4 小时前
基于机器学习方法的网球比赛胜负趋势预测
python·机器学习·django
正牌强哥4 小时前
Futures_ML——机器学习在期货量化交易中的应用与实践
人工智能·python·机器学习·ai·交易·akshare
倔强青铜三4 小时前
苦练Python第62天:零基础玩转CSV文件读写,csv模块实战
人工智能·python·面试