使用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')
相关推荐
秃了也弱了。6 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
Dfreedom.7 小时前
从 model(x) 到__call__:解密深度学习框架的设计基石
人工智能·pytorch·python·深度学习·call
weixin_425023007 小时前
Spring Boot 配置文件优先级详解
spring boot·后端·python
小徐Chao努力8 小时前
【Langchain4j-Java AI开发】06-工具与函数调用
java·人工智能·python
无心水8 小时前
【神经风格迁移:全链路压测】33、全链路监控与性能优化最佳实践:Java+Python+AI系统稳定性保障的终极武器
java·python·性能优化
luoluoal8 小时前
基于python的小区监控图像拼接系统(源码+文档)
python·mysql·django·毕业设计·源码
BoBoZz199 小时前
MotionBlur 演示简单运动模糊
python·vtk·图形渲染·图形处理
十八度的天空9 小时前
第01节 Python的基础语法
开发语言·python
BoBoZz199 小时前
GradientBackground 比较不同类型的背景渐变着色模式与坐标转换
python·vtk·图形渲染·图形处理
540_5409 小时前
ADVANCE Day32
人工智能·python·机器学习