检查远程服务是否可用的脚本,如果不可用则重启服务 and/or 网络

Script to check if remote service is available, if not restart service and/or network

我是 运行 一台供私人使用的 plex 媒体服务器,在家里的 Ubuntu 16.04 桌面虚拟机上使用。 我在一周外出工作时使用它

最近我一直被连接问题所困扰。有时是 plex 本身崩溃并需要重新启动,有时是互联网连接 (eth0) 需要重新启动。

我需要一些脚本方面的帮助,我可以通过 cron 调用该脚本来检查服务器是否可以远程访问,是否可以访问 https://external.address:32400 (请注意它只响应 https ),如果无法访问,请重新启动互联网连接(eth0),然后再次检查是否可以远程访问,如果仍然无法远程访问,则重新启动 plex 媒体服务器。

Plex 作为一项服务安装,因此调用 service plexmediaserver restart 是我重新启动它的方式。我想因为它是重启网络的桌面安装,脚本需要使用 service network-manager restart.

我找到了 this post 和脚本,但它非常陈旧和过时。

希望有人能帮我解决这个问题。

提前致谢。

您可以使用我发现的这个片段 here. You'd put in the IP address you're looking for, and then check the status code against the values found here。如果 get_status_code returns 代码 200,您可以远程访问。

import httplib

def get_status_code(host, path="/"):
    """ This function retreives the status code of a website by requesting
        HEAD data from the host. This means that it only requests the headers.
        If the host cannot be reached or something else goes wrong, it returns
        None instead.
    """
    try:
        conn = httplib.HTTPConnection(host)
        conn.request("HEAD", path)
        return conn.getresponse().status
    except StandardError:
        return None

好的,在对我的问题进行更多研究后,我发现我有两个不同的问题,有时 VM 失去它的桥接连接,有时 plex 媒体服务器崩溃。

因此,我将解决方案拆分为两个简单的 bash 脚本,我从 cron 调用它们。

首先检查互联网是否正常工作,如果不正常则重新启动虚拟机。简单地重新启动网络管理器没有用。

#!/bin/bash

PATH=/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/$

#Check if the vm can access google.com, if yes then exit
        if nc -zw1 google.com 80;
                then exit
#If it can't reach google.com restart the vm
                else shutdown -r now
        fi

第二个脚本检查是否可以访问本地的 plex 媒体服务器,如果不能,则重新启动 plex 服务。

#!/bin/bash

PATH=/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/$

#Check to see that plex is acessable locally, if yes then exit
if curl -s --head  --request GET http://localhost:32400 | grep "200 OK" > /dev/$
  then exit
#If not then restart plex service 
else
   service plexmediaserver restart
fi

感谢您的建议。这远非一个优雅的解决方案,但由于时间紧迫,这是一个解决方案。