Use argparse and ConfigParser to have only one script and automated creds saving

This commit is contained in:
Dashie 2016-12-16 22:53:00 +01:00
parent 4bb1710914
commit 318894d345
No known key found for this signature in database
GPG Key ID: C2D57B325840B755
4 changed files with 108 additions and 56 deletions

3
.gitignore vendored
View File

@ -87,3 +87,6 @@ ENV/
# Rope project settings # Rope project settings
.ropeproject .ropeproject
.credentials
.idea

View File

@ -22,7 +22,7 @@ This is what I used, you can of course adapt the collector script to talk to inf
First thing to do is to register an app, to generate a specific `freebox_app_token`. First thing to do is to register an app, to generate a specific `freebox_app_token`.
Use the `freebox_register_app.py` script. Run `python freebox_monitoring.py --register` to do that.
*PS: You can modify the app name/versions etc as shown below (Optional)* *PS: You can modify the app name/versions etc as shown below (Optional)*
@ -45,7 +45,7 @@ Head to your Freebox Server device.
Press the `>` to authorize the app registration process. Press the `>` to authorize the app registration process.
Be sure to save the `freebox_app_token` and `track_id` somewhere safe, you will need them to authenticate later on. If you need to re-auth you can delete the authorization credentials by removing the file `.credentials` in the directory where `freebox_monitor.py` is.
# Step 2: Use the script to display freebox statistics information # Step 2: Use the script to display freebox statistics information
@ -55,13 +55,6 @@ Once you have your `freebox_app_token`, the process to authenticate happens in 2
(This avoids sending the token over the network) (This avoids sending the token over the network)
Edit the `freebox_monitor.py` script and set your `freebox_app_token` and `track_id` (line 73-74)
```python
freebox_app_token = "CHANGE_THIS"
track_id = "CHANGE_THIS"
```
Then execute it, to make sure it connects and displays information. Then execute it, to make sure it connects and displays information.
![freebox monitor](freebox_monitor.png) ![freebox monitor](freebox_monitor.png)

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
# pylint: disable=C0103,C0111,W0621 # pylint: disable=C0103,C0111,W0621
from __future__ import print_function
# #
# Freebox API SDK / Docs: http://dev.freebox.fr/sdk/os/login/ # Freebox API SDK / Docs: http://dev.freebox.fr/sdk/os/login/
@ -10,10 +10,15 @@ import os
import json import json
import hmac import hmac
import time import time
import argparse
import ConfigParser
import sys
from hashlib import sha1 from hashlib import sha1
import requests import requests
VERSION = "0.4.3"
def get_challenge(freebox_app_id): def get_challenge(freebox_app_id):
api_url = 'http://mafreebox.freebox.fr/api/v3/login/authorize/%s' % freebox_app_id api_url = 'http://mafreebox.freebox.fr/api/v3/login/authorize/%s' % freebox_app_id
@ -23,7 +28,8 @@ def get_challenge(freebox_app_id):
if r.status_code == 200: if r.status_code == 200:
return r.json() return r.json()
else: else:
print 'Failed request: %s\n' % r.text print("Failed request: %s\n" % r.text)
def open_session(password, freebox_app_id): def open_session(password, freebox_app_id):
api_url = 'http://mafreebox.freebox.fr/api/v3/login/session/' api_url = 'http://mafreebox.freebox.fr/api/v3/login/session/'
@ -39,8 +45,7 @@ def open_session(password, freebox_app_id):
if r.status_code == 200: if r.status_code == 200:
return r.json() return r.json()
else: else:
print 'Failed request: %s\n' % r.text print("Failed request: %s\n" % r.text)
def get_connection_stats(headers): def get_connection_stats(headers):
@ -51,8 +56,7 @@ def get_connection_stats(headers):
if r.status_code == 200: if r.status_code == 200:
return r.json() return r.json()
else: else:
print 'Failed request: %s\n' % r.text print("Failed request: %s\n" % r.text)
def get_ftth_status(headers): def get_ftth_status(headers):
@ -63,12 +67,10 @@ def get_ftth_status(headers):
if r.status_code == 200: if r.status_code == 200:
return r.json() return r.json()
else: else:
print 'Failed request: %s\n' % r.text print('Failed request: %s\n' % r.text)
# Main def get_and_print_metrics():
if __name__ == '__main__':
freebox_app_id = "fr.freebox.seximonitor" freebox_app_id = "fr.freebox.seximonitor"
freebox_app_token = "CHANGE_THIS" freebox_app_token = "CHANGE_THIS"
track_id = "CHANGE_THIS" track_id = "CHANGE_THIS"
@ -115,10 +117,94 @@ if __name__ == '__main__':
timestamp = int(time.time()) timestamp = int(time.time())
# Output the information # Output the information
print "freebox.bytes_down %s %d" % (myData['bytes_down'], timestamp) print("freebox.bytes_down %s %d" % (myData['bytes_down'], timestamp))
print "freebox.bytes_up %s %d" % (myData['bytes_up'], timestamp) print("freebox.bytes_up %s %d" % (myData['bytes_up'], timestamp))
print "freebox.rate_down %s %d" % (myData['rate_down'], timestamp) print("freebox.rate_down %s %d" % (myData['rate_down'], timestamp))
print "freebox.rate_up %s %d" % (myData['rate_up'], timestamp) print("freebox.rate_up %s %d" % (myData['rate_up'], timestamp))
print "freebox.state %s %d" % (myData['state'], timestamp) print("freebox.state %s %d" % (myData['state'], timestamp))
print "freebox.sfp_pwr_rx %s %d" % (myData['sfp_pwr_rx'], timestamp) print("freebox.sfp_pwr_rx %s %d" % (myData['sfp_pwr_rx'], timestamp))
print "freebox.sfp_pwr_tx %s %d" % (myData['sfp_pwr_tx'], timestamp) print("freebox.sfp_pwr_tx %s %d" % (myData['sfp_pwr_tx'], timestamp))
def get_auth():
script_dir = os.path.dirname(os.path.realpath(__file__))
cfg_file = os.path.join(script_dir, ".credentials")
f = ConfigParser.RawConfigParser()
f.read(cfg_file)
try:
_ = f.get("general", "track_id")
_ = f.get("general", "app_token")
except ConfigParser.NoSectionError as err:
print("Config is invalid, auth not done.")
return None
return {'track_id': f.get('general', 'track_id'),
'app_token': f.get('general', 'app_token')}
def write_auth(auth_infos):
script_dir = os.path.dirname(os.path.realpath(__file__))
cfg_file = os.path.join(script_dir, ".credentials")
f = ConfigParser.RawConfigParser()
f.add_section("general")
f.set("general", "track_id", auth_infos['track_id'])
f.set("general", "app_token", auth_infos["app_token"])
with open(cfg_file, "wb") as authFile:
f.write(authFile)
def do_register(creds):
if creds is not None:
if 'track_id' in creds and 'app_token' in creds:
print("Already registered, exiting")
return
print("Doing registration")
headers = {'Content-type': 'application/json'}
app_info = {
'app_id': 'fr.freebox.seximonitor',
'app_name': 'SexiMonitor',
'app_version': VERSION,
'device_name': 'SexiServer'
}
json_payload = json.dumps(app_info)
r = requests.post('http://mafreebox.freebox.fr/api/v3/login/authorize/', headers=headers, data=json_payload)
register_infos = None
if r.status_code == 200:
register_infos = r.json()
else:
print('Failed registration: %s\n' % r.text)
write_auth(register_infos['result'])
print("Don't forget to accept auth on the Freebox panel !")
def register_status(creds):
if not creds:
print("Status: invalid config, auth not done.")
print("Please run `%s --register` to register app." % sys.argv[0])
return
print("Status: auth already done")
print(" track_id: %s" % creds["track_id"])
print(" app_token: %s" % creds["app_token"])
# Main
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--register', action='store_true', help="Register app with Freebox API")
parser.add_argument('-s', '--register-status', dest='status', action='store_true', help="Get register status")
args = parser.parse_args()
auth = get_auth()
if args.register:
do_register(auth)
elif args.status:
register_status(auth)
else:
get_and_print_metrics()

View File

@ -1,30 +0,0 @@
#!/usr/bin/env python
# pylint: disable=C0103,C0111
import json
import requests
def get_authorization():
api_url = 'http://mafreebox.freebox.fr/api/v3/login/authorize/'
headers = {'Content-type': 'application/json'}
app_info = {
'app_id': 'fr.freebox.seximonitor',
'app_name': 'SexiMonitor',
'app_version': '0.4.2',
'device_name': 'SexiServer'
}
json_payload = json.dumps(app_info)
r = requests.post(api_url, headers=headers, data=json_payload)
if r.status_code == 200:
return r.json()
else:
print 'Failed registration: %s\n' % r.text
if __name__ == '__main__':
resp = get_authorization()
print '[Track ID] {}'.format(resp['result']['track_id'])
print '[App token] {}'.format(resp['result']['app_token'])
print 'Press on the right arrow on the Freebox Server and validate the app registration'