【问题标题】:How to check whether my server is UP and RUNNING using Python?如何使用 Python 检查我的服务器是否已启动并正在运行?
【发布时间】:2014-01-18 23:17:26
【问题描述】:

如何在 Python 中对特定 URL 进行 HTTP 调用,然后确定服务器是否已启动和运行。

由于我最近开始使用 Python,所以不确定是否有任何此类库。

如果我打开以下网址 -

http://dbx45.dc1.host.com:8082/console

然后我打开了一些页面,这意味着我的服务器已启动并正在运行。但如果它不是 UP 和 RUNNING,那么它会在 CHROME 上像这样显示我 -

Oops! Google Chrome could not connect to http://dbx45.dc1.host.com:8082/console

在火狐上 -

Unable to connect
Firefox can't establish a connection to the server at dbx45.dc1.host.com:8082

那么我如何从 Python 中判断我的服务器是否已启动和运行?

更新:-

这是我迄今为止尝试过的 -

status = urllib2.urlopen("http://dbx45.dc1.host.com:8082/console").read()
print status

如何简化这一点以了解服务器是否已启动和运行?

【问题讨论】:

标签: python http url


【解决方案1】:

您可以使用urllib 在无法打开 URL 或给出错误代码的情况下引发错误。

exception urllib2.URLErrorhttp://docs.python.org/2/library/urllib2.html#urllib2.URLError

它还有一个reason 参数,您可以使用它来缩小问题范围。

例子:

>>> import urllib2
>>> urllib2.urlopen("http://dbx45.dc1.host.com:8082/console")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 394, in open
    response = self._open(req, data)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 412, in _open
    '_open', req)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1199, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1174, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 60] Operation timed out>

查看是否启动:

try:
    urllib2.urlopen("http://dbx45.dc1.host.com:8082/console")
except urllib2.URLError:
    print "Some error"

【讨论】:

  • 您想将您的代码包含在try except 子句中,如果出现异常,您的服务器已启动。或者不是。
  • 使用 Python 3 的代码略有不同。而不是 urllib2.urlopen 使用 urllib.request.urlopen(同样适用于 urllib2.errorurllib.error)。
【解决方案2】:

一个易于使用的库是 requests。

import requests
page = requests.get('http://dbx45.dc1.host.com:8082/console')

然后你可以像这样检查状态

page.status_code

200 表示没问题,400 或 500 表示出现问题。

【讨论】:

  • 在我的编辑器PyCharm 中写着No module named requests 知道为什么吗?
  • 这里是下载这个 python 模块的说明docs.python-requests.org/en/latest/user/install 但它通常适用于许多 python 模块
  • 我刚刚运行了代码。它给了我这样一个成功的服务器,它以&lt;Response [200]&gt; 启动并运行,但如果我只是将端口更改为 8083 而不是 8082,它会引发异常而不是返回你刚刚告诉我的任何数字.. 我们应该抓住那些然后确定这些是否已启动?
  • 有什么异常?
  • 这就是我得到的requests.exceptions.ConnectionError: HTTPConnectionPool(host='dbx45.dc1.host.com', port=8083): Max retries exceeded with url: /console (Caused by &lt;class 'socket.error'&gt;: [Errno 10061] No connection could be made because the target machine actively refused it)
【解决方案3】:

浏览器显示的错误是它们无法连接。所以我认为你所追求的是服务器是否真的在监听端口。为此,您实际上并不需要整个 URL,只需要主机和端口以及一个简单的套接字连接测试。

import sys
import socket

def servertest(argv):
    host = argv[1]
    port = int(argv[2])

    args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
    for family, socktype, proto, canonname, sockaddr in args:
        s = socket.socket(family, socktype, proto)
        try:
            s.connect(sockaddr)
        except socket.error:
            return False
        else:
            s.close()
            return True


if __name__ == "__main__":
    if servertest(sys.argv):
        print("Server is UP")
    else:
        print("Server is DOWN")

【讨论】:

    【解决方案4】:
    import os
    
    def is_server_up(ip_addr):
        return os.system('ping -c 1 ' + ip_addr + ' > /dev/null') == 0
    

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2021-04-09
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 2012-08-19
      相关资源
      最近更新 更多