-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.py
129 lines (105 loc) · 3.6 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Guifibages api provider
#
# Copyright 2015 Associació d'Usuaris Guifibages
# Author: Ignacio Torres Masdeu <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import subprocess
import ipaddress
import os
import re
from bs4 import BeautifulSoup
from flask import Flask, jsonify, request
import requests
import bot
app = Flask(__name__)
@app.route('/ping/<ip>')
@app.route('/ping/<ip>/<count>')
def pinghandler(ip, count=2):
return jsonify(ping(ip, count))
@app.route('/traceroute/<ip>')
def traceroutehandler(ip):
return jsonify(mtr(ip))
@app.route('/whois/<ip>')
def ipinfohandler(ip):
info = whois(ip)
return jsonify(info)
def whois(ip):
print("whoising: " + ip)
host = requests.get('http://guifi.net/ca/guifi/menu/ip/ipsearch/{}'.
format(ip))
s = BeautifulSoup(host.text, "html.parser")
h = s.find("th", text="nipv4").find_parent("table").find_all("td")
if len(h) == 0:
return dict(status=-1, ip=ip, text="Not found")
node = "{} (http://guifi.net{})".format(h[5].a.text, h[5].a["href"])
status = 0
return dict(status=status, ip=ip, text="Node: {}".format(node))
def traceroute(ip):
return mtr(ip)
def mtr(ip):
try:
address = ipaddress.ip_address(ip)
except ValueError:
return dict(status=-1, text="Error: Invalid IP address", ip=ip)
try:
text = subprocess.check_output(["mtr", "-r", "-c", "1", ip],
stderr=subprocess.STDOUT,
universal_newlines=True)
status = 0
except subprocess.CalledProcessError as e:
text = e.output
status = e.returncode
except Exception as e:
text = e
status = -1
return dict(status=status, ip=ip, text=text)
def ping(ip, count=2):
try:
address = ipaddress.ip_address(ip)
command = "ping"
if isinstance(address, ipaddress.IPv6Address):
command = "ping6"
except ValueError:
return dict(status=-1, text="Error: Invalid IP address", ip=ip)
try:
text = subprocess.check_output([command, '-c %d' % int(count), ip],
stderr=subprocess.STDOUT,
universal_newlines=True)
status = 0
except subprocess.CalledProcessError as e:
text = e.output
status = e.returncode
except Exception as e:
text = e
status = -1
return dict(status=status, ip=ip, text=parse_ping(text))
def parse_ping(text):
match = re.search("\s(?P<packets>\d+)\spackets\stransmitted,"
"\s(?P<received>\d+)\spackets\sreceived,\s"
"(?P<loss>\d+%)\spacket\sloss", text, re.MULTILINE)
if match is None:
return text
return match.groupdict()
@app.route('/telegram', methods=['POST'])
def telegramWebHook():
bot.Message(request.json)
return ""
if __name__ == "__main__":
bot.token = os.environ['TELEGRAM_TOKEN']
bot.app = app
client = requests.Session()
app.run(debug=True, port=8060, host="0.0.0.0")