使用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')
相关推荐
曲幽7 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
装不满的克莱因瓶8 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..8 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
金銀銅鐵8 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf8 小时前
Python 模块与包的导入导出
前端·后端·python
ice8130331819 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
copyer_xyf9 小时前
Python venv 虚拟环境
前端·后端·python
林爷万福10 小时前
GitHub 开源光谱数据处理项目推荐
python·光纤光谱仪
copyer_xyf10 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python
Full Stack Developme10 小时前
Spring Bean 依赖注入
python·spring·log4j