背景
公司需要添加新的网段,所以需要对业务所有的机器进行端口探测,看是否需要放开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')