python - 来自外部服务器的两台服务器之间的python ping
问题描述
是否可以从外部服务器在两台服务器/计算机之间 ping 通?
例子:
我们有三台服务器 A、B 和 C,从 A 运行脚本,我想测试 B 和 C 之间的 ping。
解决方案
我会采用这种方法(使用 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 个工时。
推荐阅读
- javascript - 如何禁用负值并允许输入类型数字的十进制值?
- java - 如何动态判断Java程序的运行时内存使用情况?
- mysql - 从到达和离开日期选择未预订的房间
- canvas - 如何在画布中沿路径涂抹 svg?
- javascript - 为什么我的
ReactJS 项目中的组件看不到任何道具? - excel - 如何根据另一张工作表中的数据替换自动填充范围
- python - 使用knitr编织时无法在RStudio中使用网状导入geopandas
- android - android-ndk 位于哪里?
- amazon-web-services - 使用 java 的 Kinesis 跨账户访问
- php - Laravel 存储删除/清理在生产服务器上不起作用