如何用Python脚本检测Windows与Cisco IOS并执行对应操作
解决方案:跨Windows/Cisco IOS的Python脚本系统检测与分支逻辑
一、系统检测的正确实现
1. Windows系统检测
sys.platform是属性而非方法,直接调用sys.platform即可(之前报错是误加了括号),返回值为win32/win64;platform.system()返回Windows,VS Code的警告属于环境提示,不影响脚本运行。- 检测逻辑示例:
import sys import platform def detect_os(): # 匹配Windows平台 if sys.platform.startswith('win') or platform.system() == 'Windows': return 'windows' # 匹配Cisco IOS平台 elif check_cisco_ios(): return 'cisco_ios' else: raise NotImplementedError("Unsupported OS")
2. Cisco IOS系统检测
Cisco IOS的Python环境有专属特征,可通过两种方式验证:
- 检查
sys.platform返回值:多数IOS版本返回cisco_ios或ios - 执行IOS专属CLI命令验证:比如解析
show version的输出 - 检测函数示例:
import subprocess def check_cisco_ios(): try: # 尝试执行IOS专属命令 result = subprocess.run(['show', 'version'], capture_output=True, text=True, check=True) return 'Cisco IOS' in result.stdout except (FileNotFoundError, subprocess.CalledProcessError): # 命令不可用时,直接匹配平台标识 return sys.platform in ['cisco_ios', 'ios']
注:部分IOS版本支持
cli模块,可替换为from cli import execute; execute('show version')来获取输出。
二、分支逻辑与任务处理
基于系统检测结果,分分支实现对应任务:
def main(): os_type = detect_os() if os_type == 'windows': handle_windows_tasks() elif os_type == 'cisco_ios': handle_cisco_ios_tasks() # Windows端任务处理 def handle_windows_tasks(): # 检测TFTP服务是否运行(以系统自带TFTP服务为例) def is_tftp_running(): try: result = subprocess.run(['sc', 'query', 'tftpd'], capture_output=True, text=True) return 'RUNNING' in result.stdout except: return False if not is_tftp_running(): # 调用U盘内的TFTP安装包并启动服务 subprocess.run(['./tftp_setup.exe'], check=True) subprocess.run(['sc', 'start', 'tftpd'], check=True) # 创建指定文件夹 import os for folder in ['config-archive', 'status']: if not os.path.exists(folder): os.makedirs(folder) # Cisco IOS端任务处理 def handle_cisco_ios_tasks(): # 获取TFTP服务器IP(可设置默认值) tftp_ip = input("Enter TFTP server IP: ") or '192.168.1.100' # ping检测TFTP服务器连通性 try: subprocess.run(['ping', tftp_ip, 'repeat', '4'], capture_output=True, text=True, check=True) print(f"TFTP server {tftp_ip} is reachable") except subprocess.CalledProcessError: print(f"TFTP server {tftp_ip} is unreachable") # 检查TFTP服务器上的目标文件夹(部分TFTP服务器支持ls命令) for folder in ['config-archive', 'status']: try: subprocess.run(['tftp', tftp_ip, 'ls', folder], capture_output=True, text=True, check=True) print(f"{folder} exists on TFTP server") except: print(f"{folder} missing on TFTP server") if __name__ == '__main__': main()
三、关键注意事项
- U盘运行时,确保脚本与TFTP安装包路径相对,避免绝对路径报错
- Cisco IOS可能使用Python 2.7,需适配语法(比如用
raw_input()替代input()) - Windows第三方TFTP服务的名称可能不同,需根据实际安装包调整
sc query的服务名
内容的提问来源于stack exchange,提问作者Robert T
相关产品推荐
相关产品推荐

