一.前言

最近看itdog的测速挺帅的,想着自己先做个类似的功能出来,搓了一份源码分享给大家

需求

需要主服务器放行9090端口,节点服务器放行8080端口

操作系统Centos

需要有Python环境,没有的可以看Centos部署Python代码

Python需要安装requests,flask,json,subprocess这几个库

 

二.代码

1.主服务端代码

# -*- coding:utf-8 -*-
import requests
import subprocess
from flask import Flask, make_response, jsonify
import json

app = Flask(__name__)

server=['1.1.1.1','2.2.2.2']#添加节点ip
serverch={'1.1.1.1':'香港','2.2.2.2':"美国"}#添加节点ip对应翻译,留空默认直接显示ip

@app.route('/ip=')
def hello_world(ip): # put application's code here
def get_ping_result_check(ip):

command = 'fping -e '+ip
p = subprocess.Popen([command],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)

out = p.stdout.read().decode('utf-8')
if out.find("unreachable") == -1:
return True
else:
return False
reslist = dict.fromkeys(server)
for i in range(0,len(server)):
if get_ping_result_check(server[i]):
try:
res=requests.get('http://'+server[i]+':9090/ip='+ip)
if str(res).find('500')!=-1:
reslist[server[i]]='连接超时'
else:
res=res.text
reslist[server[i]]=res.replace('\n','')
except Exception as e:
reslist[server[i]] = '节点异常'
else:
reslist[server[i]]='节点异常'

reslist=str(reslist)
for i in range(len(server)):
reslist=reslist.replace(server[i],serverch[server[i]])
reslist=eval(reslist)
response = make_response(json.dumps(reslist,ensure_ascii=False))
response.headers["Content-Type"] = "application/json;charset=UTF-8"
return response


if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
app.run(host="0.0.0.0",port=8080)

server列表是添加服务器节点的IP

serverch字典是添加服务器节点翻译的

2.节点代码

import os
import subprocess
import re
from flask import Flask
 
app = Flask(__name__)
 
 
@app.route('/ip=<ip>')
def hello_world(ip):  # put application's code here
    ping_results = []
 
    def get_ping_result(count,ip):
 
        command = 'fping -e '+ip
        p = subprocess.Popen([command],
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, shell=True)
 
        out = p.stdout.read().decode('utf-8')
        return out
    back=get_ping_result('10000', ip)
    back=back.split('(')[1]
    back=back.replace(')','')
    return back
 
if __name__ == '__main__':
    app.run(host="0.0.0.0",port=9090)

注意!节点端端口请不要改变,不然服务端会连不上

3.安装fping

fping节点服和主服都要安装

wget http://www.fping.org/dist/fping-3.13.tar.gz
tar xzvf fping-3.13.tar.gz
cd fping-3.13
./configure
make
make install

这段过程中可能会报错,没关系,不会有影响,在ssh一行一行输入进入就行了

安装好后输入fping -h出现

image-21

就代表成功安装了。

3.运行

运行主服务端和节点服务端代码,然后输入:http://主服务端ip:8080/ip=你要ping的ip或者域名

阅读剩余
THE END