如何将端口连通性检查结果写入Pandas DataFrame并导出至Excel?
实现端口检查结果写入Excel的方案
需求说明
原脚本可从Excel读取Host和Port,检查端口开放状态并打印到控制台,现需将检查结果写入新Excel文件,包含Host、Port、Status三列。
修改后的完整代码
import pandas as pd import socket from contextlib import closing from rich.console import Console input_file = "somefile.xlsx" output_file = "port_check_results.xlsx" # 定义输出文件路径 def process_excel(input_file): # 读取输入Excel文件 df = pd.read_excel(input_file, usecols='C,F') df = df.drop_duplicates() # 初始化结果列表,用于存储检查结果 results = [] for index, row in df.iterrows(): host = row["Backend"] port = row["Port"] # 获取端口检查状态,并同时打印到控制台 status = check_socket(host, port) # 将结果添加到列表 results.append({ "Host": host, "Port": port, "Status": status }) # 将结果列表转换为DataFrame result_df = pd.DataFrame(results) # 写入到新Excel文件 result_df.to_excel(output_file, index=False) print(f"检查结果已成功写入文件: {output_file}") def check_socket(host, port): console = Console(color_system="windows") with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: try: if sock.connect_ex((host, port)) == 0: status = "Open" console.print(f"{host}:{port} [green]{status}") else: status = "Closed" console.print(f"{host}:{port} [red]{status}") except Exception as e: status = f"Not Found - {str(e)}" console.print(f"{host}:{port} - [dark_orange3]Not Found[/dark_orange3] -", f"[bright_red]{e}") # 返回状态值供写入Excel使用 return status # 执行主函数 if __name__ == "__main__": process_excel(input_file)
关键修改说明
- 让
check_socket返回状态值:修改该函数,在打印控制台信息的同时,返回对应的状态字符串(Open/Closed/带异常信息的Not Found),方便后续收集结果。 - 收集结果并转换为DataFrame:在
process_excel函数中初始化一个列表,每次检查后将Host、Port、Status以字典形式添加到列表,最后转换为pandas的DataFrame。 - 写入Excel文件:使用DataFrame的
to_excel方法将结果写入指定文件,设置index=False避免生成多余的索引列。 - 新增输出文件定义:明确指定输出Excel的路径,方便用户查看结果。
内容的提问来源于stack exchange,提问作者iNeedScissors61
相关产品推荐
相关产品推荐

