Esempio n. 1
0
    def mikrotik(self, ip, ip_arr=[]):
        ip_arr.append(ip)
        #make Multithreaded
        print(ip)

        def mikrotikConnect(ip):
            list_address = api.get_resource('/ip/dhcp-server/lease')
            json_response = list_address.get()
            print(json_response)
            for interface in json_response:
                try:
                    self.interface.add(interface['host-name'])
                except KeyError:
                    print(KeyError)

        try:
            connection = routeros_api.RouterOsApiPool(
                ip,
                username=os.environ.get('omni_user'),
                password=os.environ.get('omni_pass'),
                plaintext_login=True)
            api = connection.get_api()
            mikrotikConnect(ip)
        except:
            try:
                connection = routeros_api.RouterOsApiPool(
                    ip,
                    username=os.environ.get('omni_user'),
                    password=os.environ.get('omni_pass_2'),
                    plaintext_login=True)
                api = connection.get_api()
                mikrotikConnect(ip)
            except:
                print('RouterOS Error')
Esempio n. 2
0
 def __init__(self):
     self.__host = '192.168.1.1'
     self.__username = '******'
     self.__password = ''
     self.__connection = routeros_api.RouterOsApiPool(
         self.__host, self.__username, self.__password)
     self.__api = self.__connection.get_api()
Esempio n. 3
0
 def post(self, request):
     data = dict()
     now = timezone.now()
     validator = Voucher.objects.filter(
         profile_id=self.request.user.profile.id,
         date_created__day=now.day).count()
     if validator > 0:
         data['valid'] = False
         data['message_type'] = error
         data['message_title'] = "Limit 1 Voucher per day"
     else:
         if request.method == 'POST':
             voucher = str(random.randint(0000000000, 9999999999))
             connection = routeros_api.RouterOsApiPool(
                 '10.10.1.1', username='******', password='******')
             print(connection)
             api = connection.get_api()
             list_queues = api.get_resource('/ip/hotspot/user')
             list_queues.add(name=voucher,
                             profile="LIMIT 12HOURS",
                             limit_uptime="10:00:00")
             form = VoucherForm(request.POST, request.FILES)
             if form.is_valid():
                 form.instance.voucher = voucher
                 form.instance.profile_id = self.request.user.profile.id
                 form.save()
                 data['valid'] = True
                 data['message_type'] = success
                 data['message_title'] = 'Successfully saved.'
                 data['url'] = reverse('main_voucher')
     return JsonResponse(data)
Esempio n. 4
0
def main():
    """Main probe function
    Returns:
    int: 0 if ok, 100 if fail
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("-u", "--user", dest="user", default=os.getenv("ROUTEROS_API_USERNAME", 'api_read_user'))
    parser.add_argument("-p", "--password", dest="password",
                        default=os.getenv("ROUTEROS_API_PASSWORD", 'do_not_expose_password_here'))
    parser.add_argument("-P", "--port", dest="port", type=int, default=os.getenv("ROUTEROS_API_PORT", 8728))
    parser.add_argument("-H", "--host", required=True, dest="host")
    parser.add_argument("--path", required=True, dest="path")
    args = parser.parse_args()
    try:
        api = routeros_api.RouterOsApiPool(args.host,
                                           port=args.port,
                                           username=args.user,
                                           password=args.password,
                                           plaintext_login=True).get_api()
        for address in api.get_resource(args.path).get():
            logging.info(address)
    except Exception as e:
        logging.error(e)
        return 100
    return 0
Esempio n. 5
0
 def post(self, request):
     data = dict()
     if request.method == 'POST':
         mikrotik = Mikrotik.objects.first()
         try:
             connection = routeros_api.RouterOsApiPool(
                 mikrotik.ip_address,
                 username=mikrotik.username,
                 password=mikrotik.password)
             api = connection.get_api()
             list_queues = api.get_resource('/ip/hotspot/user')
             number_ticket = Number_TicketForm(request.POST, request.FILES)
             if number_ticket.is_valid():
                 ticket = number_ticket.save()
                 number_ticket = Number_Ticket.objects.get(id=ticket.id)
                 user_profile = User_Profile.objects.get(
                     id=number_ticket.user_profile_id)
                 for p in range(number_ticket.number_ticket):
                     string_random = random_char(5)
                     username = str(
                         number_ticket.prefix) + str(string_random)
                     print(username)
                     list_queues.add(name=username,
                                     profile=user_profile.user_profile,
                                     limit_uptime=user_profile.uptime_limit)
                     Voucher.objects.create(number_ticket=number_ticket,
                                            username=username)
                 data['message_type'] = success
                 data['message_title'] = 'Successfully generated.'
                 data['url_print'] = reverse(
                     'voucher_print', kwargs={'pk': number_ticket.id})
         except Exception as e:
             data['message_type'] = error
             data['message_title'] = 'Connection ' + str(e)
     return JsonResponse(data)
Esempio n. 6
0
 def __init__(self, ip_bts, user_bts, pw_bts):
     self.ip_bts = ip_bts
     self.user_bts = user_bts
     self.pw_bts = pw_bts
     self.api = routeros_api.RouterOsApiPool(
         self.ip_bts, self.user_bts, self.pw_bts,
         plaintext_login=True).get_api()
Esempio n. 7
0
def login():
    session['logedin'] = False
    if 'username' in request.args and 'password' in request.args:
        #ambil data username dan password yang dikirim oleh browser
        username = request.args['username']
        password = request.args['password']
        #persiapkan koneksi ke router
        koneksi = routeros_api.RouterOsApiPool('192.168.1.100',
                                               username=username,
                                               password=password)
        try:
            #proses login ke router
            api = koneksi.get_api()
            output = {'state': True, 'message': 'Login berhasil'}
            session['logedin'] = True
            session['username'] = username
            session['password'] = password
        except:
            output = {
                'state': False,
                'message': 'Login gagal! Username/password salah'
            }
    else:
        output = {'state': False, 'message': 'Username/password belum lengkap'}
    return jsonify(output)
Esempio n. 8
0
def sent_cmd_to_ros(ip, username, password, cmd):
    logging.info('{} has answer:'.format(ip))
    connection = routeros_api.RouterOsApiPool(ip, username=username, password=password, plaintext_login=True)
    api = connection.get_api()
    answer = api.get_resource(cmd)
    answer = answer.get()
    connection.disconnect()
    return answer
Esempio n. 9
0
def ros_api():
    try:
        connection = routeros_api.RouterOsApiPool(cfg.IP, **cfg.ROS_API_KWARGS)
        api = connection.get_api()
        return api
    except ros_exc.RouterOsApiConnectionError:
        logger.error("ROS_API Connection fail")
        return False
Esempio n. 10
0
def connect(host, username, password):
    connection = routeros_api.RouterOsApiPool(host,
                                              username=username,
                                              password=password,
                                              port=8740,
                                              plaintext_login=True)
    api = connection.get_api()
    print('Conexión Establecida')
    return api, connection
Esempio n. 11
0
def connectRouter(ipaddr):
    '''
	return a router connection entity from its ip address
	'''
    connection = routeros_api.RouterOsApiPool(ipaddr,
                                              username='******',
                                              password='')
    router = connection.get_api()
    return router
def set_control(request):
    tog, created = toogle.objects.get_or_create(id=1)
    if "GET" == request.method:
        return render(request, "control.html", {'tog': tog})
    elif "POST" == request.method:
        tog = toogle.objects.get(id=request.POST['id'])
        tog.is_working = request.POST['isworking'] == 'true'
        tog.save()

        # taking configuration value
        con = configuration.objects.last()
        inf_ip = con.oinflux.host
        inf_port = con.oinflux.ports
        inf_database = con.oinflux.database
        sh = con.oshared.id
        sh_id = str(int(sh) - 1)
        sh_up = con.oshared.pmaxlimitup
        sh_down = con.oshared.pmaxlimitdown
        sh_name = con.oshared.pname
        ded_name = con.odedicated.pname
        ded_down = con.odedicated.pmaxlimitdown

        # influx db
        client = InfluxDBClient(host='localhost',
                                port=8086,
                                database='telegraf')

        # mikrotik
        connection = routeros_api.RouterOsApiPool('10.33.109.121',
                                                  username='******',
                                                  password='******',
                                                  port=8738,
                                                  plaintext_login=True)
        api = connection.get_api()
        simple = api.get_resource('/queue/simple')

        # multithreading
        while tog.is_working == True:
            tog = toogle.objects.get(id=1)
            if tog.is_working == True:
                que_mean = "SELECT derivative(mean(Download),1s) AS Download FROM \"" + str(
                    ded_name
                ) + "\" where time>= now()- 15s group by time(1s) fill(null) tz('Asia/Jakarta')"
                query = "SELECT derivative(mean(Download),1s) AS Download FROM \"" + str(
                    ded_name
                ) + "\" where time>= now()- 24h group by time(1s) fill(null) tz('Asia/Jakarta')"
                result = client.query(query)
                res_mean = client.query(que_mean)
                point = list(result.get_points())
                po_mean = list(res_mean.get_points())
                set_autocontrol(simple, point, po_mean, sh_up, sh_down, client,
                                sh_id)
                time.sleep(5)
            else:
                set_falsecontrol(simple, sh_up, sh_down, sh_id)
    return HttpResponse('success')
Esempio n. 13
0
 def connect_api(self):
     connection = routeros_api.RouterOsApiPool(
         host=self._address,
         username=self._username,
         password=self._password,
         use_ssl=True,
         ssl_context=self._ssl_context,
         plaintext_login=True,
     )
     self.api = connection.get_api()
Esempio n. 14
0
def connect_router():
    global start
    connection = routeros_api.RouterOsApiPool('192.168.100.1',port=3311, username='******', password='******',plaintext_login=True)
    connect_object.append(connection)
    api = connection.get_api()
    while True:
        data = convert_to_dict(str(api.get_resource('/').call('ping', { 'address': '192.168.100.208', 'count': '1'})))
        if data["received"] == '0':
            print("time out")
        else:
             print(data["time"])
def get_connection(args):
    connection = None
    try:
        connection = routeros_api.RouterOsApiPool(args.host,
                                                  port=args.port,
                                                  username=args.user,
                                                  password=args.password,
                                                  plaintext_login=True)
    except RouterOsApiConnectionError as e:
        logging.error("Unable to connect {}: {}".format(args.host, e))
    return connection
Esempio n. 16
0
def home():
    if session['logedin'] == True:
        koneksi = routeros_api.RouterOsApiPool('192.168.1.100',
                                               username=session['username'],
                                               password=session['password'])
        api = koneksi.get_api()
        #ambil data user yang ada di router
        ip = api.get_resource("/ip/address").get()
        return render_template("home.html", data=ip)
    else:
        return render_template("index.html")
Esempio n. 17
0
 def conn_mikrotik(self):
     try:
         self.connection = routeros_api.RouterOsApiPool(host=config['mikrotik']['host'],
                                                        username=config['mikrotik']['username'],
                                                        password=config['mikrotik']['password'],
                                                        port=config['mikrotik']['port'])
         self.api = self.connection.get_api()
     except Exception as e:
         print (ROUTER, str(e))
         logger = logging.getLogger("conn_mikrotik()")
         logger.error(str(e))
         exit(1)
Esempio n. 18
0
def show_ipactive(parameter_list):
    host = "192.168.31.1"
    conn = routeros_api.RouterOsApiPool(
        host, username="******", password="", plaintext_login=True)
    api = conn.get_api()

    list_ip = api.get_resource('ip/address')
    show_ip = list_ip.get()

    data = json.dumps(show_ip, indent=3)
    conn.disconnect()
    return show_ip
    pass
 def __init__(self, **kwargs):
     self.routerboard_name = kwargs.pop('routerboard_name')
     self.interface = kwargs.pop('interface')
     self.wireless = kwargs.pop('wireless')
     self.caps_man = kwargs.pop('caps_man')
     self.l2tp = kwargs.pop('l2tp')
     self.gre = kwargs.pop('gre')
     try:
         self.connection = routeros_api.RouterOsApiPool(**kwargs)
         self.connection.socket_timeout = 1
         self.api = self.connection.get_api()
     except routeros_api.exceptions.RouterOsApiConnectionError as e:
         raise ConnectionError(
             f'{self.routerboard_name} is not connected: {e}')
def run(config):
    connection = routeros_api.RouterOsApiPool(config['ROUTER_HOST'],
                                              username=config['ROUTER_USER'],
                                              password=config['ROUTER_PASS'])
    api = connection.get_api()
    iso_now = datetime.datetime.now().replace(microsecond=0).isoformat()

    redis_connection = redis.from_url(config['REDIS_URL'])

    # Ask the device for a list of ARP table entries, and filter the ones out
    # which do not have a MAC address.
    arp_entries = api.get_resource('/ip/arp')
    addresses = set([entry['mac-address'] for entry in arp_entries.get()
                    if 'mac-address' in entry])

    logging.info("Found {} mac addresses in the ARP table: {}"
                 .format(len(addresses), addresses))

    # Set "updated-at" to show that we've successfully retrieved the new data
    # from the device.
    redis_connection.set('mac-addresses-updated-at', iso_now)

    # Pull the previous address list out of redis for comparison.
    previous_addresses = redis_connection.lrange('mac-addresses', 0, -1) or []
    previous_addresses = set([a.decode() for a in previous_addresses])

    if addresses != previous_addresses:
        logging.info("Address list has changed, replace with new list.")

        transaction = redis_connection.pipeline()
        transaction.delete('mac-addresses')
        transaction.lpush('mac-addresses', *addresses)
        # Set "changed-at" to indicate that the contents of the list actually
        # changed at this time.
        transaction.set('mac-addresses-changed-at', iso_now)
        transaction.execute()

        online = addresses - previous_addresses
        offline = previous_addresses - addresses

        for address in online:
            logging.info("{} came online, emitting update.".format(address))
            redis_connection.publish('mac-address-online', address)

        for address in offline:
            logging.info("{} went offline, emitting update.".format(address))
            redis_connection.publish('mac-address-offline', address)
Esempio n. 21
0
def RouterOs_Query(cmd='/system/identity',
                   router_ip='8.8.8.8',
                   username='******',
                   password='******'):

    try:
        connection = routeros_api.RouterOsApiPool(router_ip, username,
                                                  password)
        api = connection.get_api()
        print("\n################ connecting router #################\n")
        result = api.get_resource(cmd).get()
        connection.disconnect()
        print(result)
        return result

    except:
        print('\nsomething goes wrong while deal with Router, please check')
Esempio n. 22
0
    def __init__(self,
                 ros_ip,
                 username='******',
                 password='',
                 port=8728,
                 plaintext_login=False,
                 use_ssl=False,
                 ssl_verify=True,
                 ssl_verify_hostname=True,
                 ssl_context=None):

        # credentials saves to global
        self._mikrotik_ip = ros_ip
        self._username = username
        self._password = password
        self._port = port
        self._plaintext_login = plaintext_login
        self._use_ssl = use_ssl
        self._ssl_verify = ssl_verify
        self._ssl_verify_hostname = ssl_verify_hostname
        self._ssl_context = ssl_context

        try:
            # connecting with ros
            self.connection = routeros_api.RouterOsApiPool(
                host=self._mikrotik_ip,
                username=self._username,
                password=self._password,
                port=self._port,
                plaintext_login=self._plaintext_login,
                use_ssl=self._use_ssl,
                ssl_verify=self._ssl_verify,
                ssl_verify_hostname=self._ssl_verify_hostname,
                ssl_context=self._ssl_context)
            '''self.connection.set_timeout(5)
            self.api = self.connection.get_api()'''
            # print(connection.connected)
        except Exception as rce:
            print(':Error: connecting with routerOS! {}'.format(rce))

        # self.connection = None
        self.api = None
Esempio n. 23
0
def main():
    home = os.path.dirname(os.path.abspath(__file__))
    os.chdir(home)

    config = ConfigParser.RawConfigParser()
    config.read('application.conf')
    data_dir = config.get('application', 'data_dir')
    boxes = json.loads(config.get('application', 'boxes_json'))

    logging.config.fileConfig('logging.conf')

    setup_encoding()

    for box in boxes:
        host = box['host']
        login = box['login']
        password = box['password']

        try:
            logging.info("Processing %s", host)
            connection = routeros_api.RouterOsApiPool(host,
                                                      username=login,
                                                      password=password)
            api = connection.get_api()
            resource = api.get_resource('/ip/arp')
            entries = resource.get(
            )  # List of {u'complete': u'true', u'published': u'false', u'dynamic': u'true', u'invalid': u'false', u'mac-address': u'00:12:34:56:78:9A', u'disabled': u'false', u'address': u'10.9.8.7', u'interface': u'v1234', u'DHCP': u'false', u'id': u'*BDF'}
            data = set([(entry['mac-address'], entry['interface'])
                        for entry in entries if 'mac-address' in entry])
            file_name = datetime.now().strftime(
                '%Y%m%d%H%M%S') + '-' + host + '.gz'
            file_path = os.path.join(data_dir, file_name)
            with gzip.open(file_path, 'wb') as file:
                for obj in data:
                    file.write(' '.join(obj) + '\n')
            logging.info("%s done", host)
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            logging.error(exc_value)
            pass
        finally:
            connection.disconnect()
Esempio n. 24
0
def connect_router():
    global start
    connection = routeros_api.RouterOsApiPool('192.168.100.1',
                                              port=3311,
                                              username='******',
                                              password='******',
                                              plaintext_login=True)
    connect_object.append(connection)
    api = connection.get_api()
    # print(api.get_resource('/queue'))
    # command = api.get_resource(input("Command ").lower())
    output = time.time()
    print("%.3f" % (output - start))
    start = output
    while True:
        print(
            convert_to_dict(
                str(
                    api.get_resource('/').call('ping', {
                        'address': '192.168.100.201',
                        'count': '1'
                    })))["time"])
Esempio n. 25
0
    def post(self, request):
        data = dict()
        if request.method == 'POST':
            form = Generate_TicketForm(request.POST, request.FILES)
            mikrotik = Mikrotik.objects.first()
            # MIKROTIK
            connection = routeros_api.RouterOsApiPool(
                mikrotik.ip_address,
                username=mikrotik.username,
                password=mikrotik.password)
            print(connection)
            try:
                api = connection.get_api()
                list_queues = api.get_resource('/ip/hotspot/user')
                # MIKROTIK CREATE USER
                if form.is_valid():
                    ticket = form.save()
                    for p in range(form.instance.no_ticket):
                        # GENERATE RANDOM TICKETS
                        voucher = str(random.randint(0000000, 9999999))
                        list_queues.add(
                            name=voucher,
                            profile=mikrotik.user_profile,
                            limit_uptime=mikrotik.user_limit_uptime)
                        Voucher.objects.create(generate_ticket_id=ticket.id,
                                               voucher=voucher)
                    data['message_type'] = success
                    data['message_title'] = 'Successfully saved.'
                    data['url_print'] = reverse('internet_ticket_print',
                                                kwargs={'pk': ticket.id})
                    data['url'] = reverse('internet_ticket')
            except Exception as e:
                data['message_type'] = error
                data['message_title'] = 'Connection ' + str(e)

        return JsonResponse(data)
Esempio n. 26
0
def main():
    # Your @wifi.id username
    username = '******'

    # Your @wifi.id password
    password = '******'

    # Get MikroTik WLAN IP address (wlan1 interface connected to @wifi.id) via RouterOS API
    mikrotik_connection = routeros_api.RouterOsApiPool(
        '<your mikrotik IP address>',
        username='******',
        password='******')
    mikrotik_api = mikrotik_connection.get_api()
    mikrotik_wan_ip = mikrotik_api.get_resource('/ip/address')
    mikrotik_wan_ip = str(mikrotik_wan_ip.get(interface='wlan1')).replace(
        "\'", "\"")
    mikrotik_wan_ip = json.loads(mikrotik_wan_ip[1:-1])['address']
    mikrotik_wan_ip = mikrotik_wan_ip.split('/')[0]
    mikrotik_connection.disconnect()

    # IP address of your connected device/interface to @wifi.id
    client_ip = mikrotik_wan_ip

    # Your @wifi.id login page link. It usually starts with https://welcome2.wifi.id/login/...
    login_page_url = '<https://welcome2.wifi.id/login/...>'

    # Create wifi_id object
    wifi_id = Wifi(username, password, client_ip)

    # Login to @wifi.id with params from login URL
    got_response, msg = wifi_id.login_with_url(login_page_url)

    if got_response:
        print("Server response: " + str(msg))
    else:
        print("Login failed. " + str(msg))
Esempio n. 27
0
def getmetrics():
    try:
        connection = routeros_api.RouterOsApiPool(ip,
                                                  port=port,
                                                  username=user,
                                                  password=password,
                                                  plaintext_login=True)
        api = connection.get_api()

        listone = api.get_resource('/system/identity')
        listtwo = api.get_resource('/interface/')

        devicename = (listone.get()[0]['name'].replace(" ", ""))

        for i in listtwo.get():
            print ("mikrotik,device="+devicename+",interface="+i['name'].replace("<", "").replace(">", "")+\
            " rx-byte="+i['rx-byte']+" "+str(int(round(time.time() * 1000000000))))
            print ("mikrotik,device="+devicename+",interface="+i['name'].replace("<", "").replace(">", "")+\
            " tx-byte="+i['tx-byte']+" "+str(int(round(time.time() * 1000000000))))

        connection.disconnect()
    except:
        print('Can not make connection onto router! Exit...')
        sys.exit(1)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import routeros_api
import json
from lib import *
import time

conn = routeros_api.RouterOsApiPool('10.4.1.1',
                                    username='******',
                                    password='******',
                                    plaintext_login=True)

api = conn.get_api()

lista = api.get_resource('/ip/route')

ident = (lista.get(comment='ZIMBRA')[0]['id'])
stats = (lista.get(comment='ZIMBRA')[0]['disabled'])

if stats == 'true':
    point = ['T3 Dedicado **', 'Vivo Adsl', 'Sair']
else:
    point = ['T3 Dedicado', 'Vivo Adsl <=', 'Sair']

while True:

    resposta = menu(point)

    if resposta == 1:
        lista.set(id=ident, disabled="true")
Esempio n. 29
0
                    else:

                        print(f'пароль для {secret.get("name")}: {row["newpassword"]}. Его ID {profile_id}')
                        set_password.set(id=profile_id, password=row["newpassword"])    # внос изменений в MikroTik


while True:
    try:

        ip_address = input('ip-адрес Микротика: ')
        username = input('Пользователь: ')
        password = input('Пароль: ')

        connection = routeros_api.RouterOsApiPool(ip_address,
                                                  username=username,
                                                  password=password,
                                                  port=8728,
                                                  use_ssl=False,
                                                  plaintext_login=True)
        api = connection.get_api()
        break

    except routeros_api.exceptions.RouterOsApiCommunicationError:
        print('Неверные данные авторизации')
        continue

    except routeros_api.exceptions.RouterOsApiConnectionError:
        print('Устройство не найдено, проверьте IP')
        continue


print('\n Если у вас нет файла для рассылки, программа может его сформировать. \n'
Esempio n. 30
0
import time
import routeros_api
from flask import Flask, render_template, redirect, url_for, request, flash

app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
connection = routeros_api.RouterOsApiPool('gateway.loc',
                                          username='******',
                                          password='******',
                                          plaintext_login=True)

status_whitelist = [
    'id', 'name', 'type', 'last-link-down-time', 'last-link-up-time',
    'running', 'disabled', 'comment', 'Ingress', 'Egress'
]


@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        state = 'off' if is_enabled(request.form['if_id']) else 'on'
        flash(
            f"Interface {request.form['if_name']} ({request.form['if_id']}) switched {state}."
        )
        if_switch(request.form['if_id'])

    # status = if_status()
    return render_template('index.j2', if_status=if_status())


def is_enabled(id):