检查 ubuntu 服务是否已在 c# 中停止的最佳方法

Best way to check if ubuntu service has stopped in c#

我想在 Azure 虚拟机 (Ubuntu 16.04) 中的服务(grafana 或 influxdb)停止时收到警报。我想使用 c# 连接到 VM 并检查 grafana 和 influxdb 服务的状态。谁能分享实现此功能的代码示例?

您可以使用以下内容在 c#

中使用 SSH 连接到 Azure linux

using (var client = new SshClient("my-vm.cloudapp.net", 22, "username", "password​"))
        {
            client.Connect();
            Console.WriteLine("it worked!");
            client.Disconnect();
            Console.ReadLine();
        }

通常 SSH 服务器只允许 public 密钥验证或其他双因素验证。

更改您的 /etc/ssh/sshd_configuncomment #PasswordAuthentication yes

# Change to no to disable tunnelled clear text passwords
 #PasswordAuthentication yes

稍后您可以轮询已安装的服务。

还有一个替代解决方案,您可以在 linux VM 中部署一个 rest api 来检查您的服务状态并从 C# httpclient 调用它状态。

希望对您有所帮助

这两种服务都提供健康端点,可用于从远程服务器检查其状态。无需打开远程 shell 连接。事实上,如果必须通过 SSH 连接到每个服务器群,就不可能监控大型服务器群。

在最简单的情况下,忽略网络问题,只需点击运行状况端点即可检查两种服务的状态。粗略的实现可能如下所示:

public async Task<bool> CheckBoth()
{
    var client = new HttpClient
    {
        Timeout = TimeSpan.FromSeconds(30)
    };

    const string grafanaHealthUrl = "https://myGrafanaURL/api/health";
    const string influxPingUrl = "https://myInfluxURL/ping";

    var (grafanaOK, grafanaError) = await CheckAsync(client, grafanaHealthUrl,
                                                     HttpStatusCode.OK, "Grafana error");
    var (influxOK, influxError) = await CheckAsync(client, influxPingUrl, 
                                                   HttpStatusCode.NoContent,"InfluxDB error");

    if (!influxOK || !grafanaOK)
    {
                //Do something with the errors
                return false;
    }
    return true;

}

public async Task<(bool ok, string result)> CheckAsync(HttpClient client,
                                                       string healthUrl, 
                                                       HttpStatusCode expected,
                                                       string errorMessage)
{
    try
    {
        var status = await client.GetAsync(healthUrl);
        if (status.StatusCode != expected)
        {
            //Failure message, get it and log it
            var statusBody = await status.Content.ReadAsStringAsync();
            //Possibly log it ....
            return (ok: false, result: $"{errorMessage}: {statusBody}");
        }
    }
    catch (TaskCanceledException)
    {
        return (ok: false, result: $"{errorMessage}: Timeout");
    }
    return (ok: true, "");
}

也许更好的解决方案是定期使用 Azure Monitor ping the health URLs 并在它们关闭时发送警报。