首页 > 解决方案 > 来自外部服务器的两台服务器之间的python ping

问题描述

是否可以从外部服务器在两台服务器/计算机之间 ping 通?

例子:

我们有三台服务器 A、B 和 C,从 A 运行脚本,我想测试 B 和 C 之间的 ping。

标签: pythonpython-3.xbashpython-2.7

解决方案


我会采用这种方法(使用 python 脚本的其他可行解决方案可能是通过从 A 到 B 和 C 的 SSH 隧道进行此操作)。我在下面有点犹豫,但代码应该与评论相当准确......

/api/ping在 B 和 C 中使用 Flask创建 REST API 函数

from flask import json, request
import subprocess

def callPing(ip):
   # this returns True|False, but other `subprocess` methods can return more info from called Linux command
   if subprocess.check_output(["ping", "-c", "1", ip]):
       return "OK"
   else:
       return "Fail"

@app.route('/ping', methods = ['POST'])
def ping():

    ip = str(request.data) # if in POST body, plain
    ip = request.json["ip"] # body (f.ex.) {"ip":"127.0.0.1"} and headers has Content-Type: application/json

    txt = callPing(ip)
    request.headers['Content-Type'] == 'text/plain':
        return txt

从 A 向 B 和/或 C 发送 POST 请求

import requests
from json import dumps

targetIP = '8.8.8.8'
serverIP = '127.0.0.1'

data = {'user_name': targetIP }
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
url = "http://"+serverIP+"/api/ping"
r = requests.post(url, headers=headers, data=dumps(data))

如果 API 可以使用端口 80,则在现有 Linux 服务器中安装 Flask REST API 需要 1-3 个工时。


推荐阅读