You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python检查局域网内Ubuntu服务器的服务状态

用Python检查局域网内Ubuntu 22.04服务器的服务状态

要实现这个需求,核心是通过SSH远程执行系统命令查询服务状态,以下是具体的实现方案:

前提条件

  • 目标服务器已开启SSH服务,本地机器可通过密钥或密码登录(推荐密钥登录,更安全便捷)
  • 本地Python环境安装paramiko库(用于SSH连接)

安装依赖

在本地终端执行:

pip install paramiko

实现代码

下面是可直接使用的脚本,支持指定服务器地址和服务名称查询状态:

import paramiko

def check_service_status(server_ip, service_name, ssh_username, ssh_password=None, ssh_key_path=None):
    ssh_client = paramiko.SSHClient()
    # 生产环境建议手动维护known_hosts,替代自动添加策略
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        # 优先使用密钥登录
        if ssh_key_path:
            private_key = paramiko.RSAKey.from_private_key_file(ssh_key_path)
            ssh_client.connect(server_ip, username=ssh_username, pkey=private_key)
        else:
            ssh_client.connect(server_ip, username=ssh_username, password=ssh_password)
        
        # 执行服务状态查询命令
        command = f"systemctl is-active {service_name}"
        stdin, stdout, stderr = ssh_client.exec_command(command)
        
        status = stdout.read().decode().strip()
        error = stderr.read().decode().strip()
        
        if error:
            return f"查询失败: {error}"
        elif status == "active":
            return f"服务{service_name}运行正常(状态:active)"
        else:
            return f"服务{service_name}未运行(状态:{status})"
            
    except Exception as e:
        return f"连接失败: {str(e)}"
    finally:
        ssh_client.close()

# 示例调用
if __name__ == "__main__":
    # 替换为你的实际参数
    target_server = "192.168.1.100"
    target_service = "my_service1.service"
    ssh_user = "ubuntu"
    ssh_key_path = "/home/your_local_user/.ssh/id_rsa"
    
    result = check_service_status(target_server, target_service, ssh_user, ssh_key_path=ssh_key_path)
    print(result)

关键说明

  • 命令选择:systemctl is-active会直接返回active/inactive/failed等明确状态,适合脚本解析
  • 安全性:生产环境禁用AutoAddPolicy,手动维护known_hosts;避免硬编码密码,优先使用SSH密钥
  • 批量扩展:若需检查多台服务器,可将服务器IP和服务名存入列表,循环调用check_service_status函数

内容的提问来源于stack exchange,提问作者Fresto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:52:35