Update a Cloudflare DNS record with the router's public IP every 5 minutes.
import librouteros, requests, timeROUTER_IP = '192.168.88.1' API_USER = 'api_user' API_PASS = 'api_pass' CLOUDFLARE_ZONE = 'your_zone_id' CLOUDFLARE_RECORD = 'your_record_id' CLOUDFLARE_TOKEN = 'bearer_token'
def get_public_ip(api): # Get public IP from router's WAN interface addresses = api.path('ip', 'address') for addr in addresses: if addr['interface'] == 'ether1' and not addr['address'].startswith('192.168'): return addr['address'].split('/')[0] return None
def update_cloudflare(ip): url = f"https://api.cloudflare.com/client/v4/zones/CLOUDFLARE_ZONE/dns_records/CLOUDFLARE_RECORD" headers = 'Authorization': f'Bearer CLOUDFLARE_TOKEN', 'Content-Type': 'application/json' data = 'type': 'A', 'name': 'dynamic.example.com', 'content': ip, 'ttl': 120 requests.put(url, headers=headers, json=data)
def main(): api = librouteros.connect(host=ROUTER_IP, username=API_USER, password=API_PASS) while True: public_ip = get_public_ip(api) update_cloudflare(public_ip) time.sleep(300) # 5 minutes
if name == 'main': main()
Change queue max-limit at 9 AM and 6 PM.
import datetime, timedef set_bandwidth(api, upload, download): queue = api.path('queue', 'simple') # Assuming queue named 'office' queue.update('office', max_limit=f'uploadM/downloadM')
def scheduler_loop(): api = librouteros.connect(...) while True: now = datetime.datetime.now().time() if datetime.time(9,0) <= now <= datetime.time(9,5): set_bandwidth(api, 100, 20) # 100M/20M daytime elif datetime.time(18,0) <= now <= datetime.time(18,5): set_bandwidth(api, 10, 2) # 10M/2M night time.sleep(60)
scheduler_loop()
Limit a specific IP to 5Mbps download / 2Mbps upload.
queue = api.path('queue', 'simple').add(
name='customer-001',
target='192.168.88.100/32',
max_limit='5M/2M', # upload/download
comment='API traffic limit'
)
# Scan for APs def scan_wireless(interface='wlan1'): results = api('/interface/wireless/scan', 'interface': interface, 'duration': '5', 'once': '' ) for ap in results: print(f"ap['ssid'] - ap['signal-strength'] dBm - ap['address']")
curl -k -s -X PUT "https://$HOST:$PORT/rest/ip/firewall/filter"
-b cookies.txt
-H "content-type: application/json"
-d '"chain":"input","protocol":"tcp","dst-port":"22","action":"drop","comment":"API added"'
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
client := &http.Client{}
url := "https://ROUTER_IP/rest/ip/address"
payload := map[string]string"address":"192.0.2.40/24","interface":"ether1"
b, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(b))
req.SetBasicAuth("admin","yourpass")
req.Header.Set("Content-Type","application/json")
resp, err := client.Do(req)
if err != nil panic(err)
defer resp.Body.Close()
fmt.Println("Status:", resp.Status)
}
For binary API in Go, use packages like github.com/go-routeros/routeros.
queues = api('/queue/simple/print', '?name': 'user1') if queues: api('/queue/simple/remove', '.id': queues[0]['.id'])
# Disable an interface
api('/interface/set',
'.id': 'ether2',
'disabled': 'yes'
)
Mikrotik Api Examples Review
Update a Cloudflare DNS record with the router's public IP every 5 minutes.
import librouteros, requests, time
ROUTER_IP = '192.168.88.1'
API_USER = 'api_user'
API_PASS = 'api_pass'
CLOUDFLARE_ZONE = 'your_zone_id'
CLOUDFLARE_RECORD = 'your_record_id'
CLOUDFLARE_TOKEN = 'bearer_token'
def get_public_ip(api):
# Get public IP from router's WAN interface
addresses = api.path('ip', 'address')
for addr in addresses:
if addr['interface'] == 'ether1' and not addr['address'].startswith('192.168'):
return addr['address'].split('/')[0]
return None
def update_cloudflare(ip):
url = f"https://api.cloudflare.com/client/v4/zones/CLOUDFLARE_ZONE/dns_records/CLOUDFLARE_RECORD"
headers = 'Authorization': f'Bearer CLOUDFLARE_TOKEN', 'Content-Type': 'application/json'
data = 'type': 'A', 'name': 'dynamic.example.com', 'content': ip, 'ttl': 120
requests.put(url, headers=headers, json=data)
def main():
api = librouteros.connect(host=ROUTER_IP, username=API_USER, password=API_PASS)
while True:
public_ip = get_public_ip(api)
update_cloudflare(public_ip)
time.sleep(300) # 5 minutes mikrotik api examples
if name == 'main':
main()
Change queue max-limit at 9 AM and 6 PM.
import datetime, time
def set_bandwidth(api, upload, download):
queue = api.path('queue', 'simple')
# Assuming queue named 'office'
queue.update('office', max_limit=f'uploadM/downloadM') Update a Cloudflare DNS record with the router's
def scheduler_loop():
api = librouteros.connect(...)
while True:
now = datetime.datetime.now().time()
if datetime.time(9,0) <= now <= datetime.time(9,5):
set_bandwidth(api, 100, 20) # 100M/20M daytime
elif datetime.time(18,0) <= now <= datetime.time(18,5):
set_bandwidth(api, 10, 2) # 10M/2M night
time.sleep(60)
scheduler_loop()
Limit a specific IP to 5Mbps download / 2Mbps upload. Change queue max-limit at 9 AM and 6 PM
queue = api.path('queue', 'simple').add(
name='customer-001',
target='192.168.88.100/32',
max_limit='5M/2M', # upload/download
comment='API traffic limit'
)
# Scan for APs
def scan_wireless(interface='wlan1'):
results = api('/interface/wireless/scan',
'interface': interface,
'duration': '5',
'once': ''
)
for ap in results:
print(f"ap['ssid'] - ap['signal-strength'] dBm - ap['address']")
curl -k -s -X PUT "https://$HOST:$PORT/rest/ip/firewall/filter"
-b cookies.txt
-H "content-type: application/json"
-d '"chain":"input","protocol":"tcp","dst-port":"22","action":"drop","comment":"API added"'
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
client := &http.Client{}
url := "https://ROUTER_IP/rest/ip/address"
payload := map[string]string"address":"192.0.2.40/24","interface":"ether1"
b, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(b))
req.SetBasicAuth("admin","yourpass")
req.Header.Set("Content-Type","application/json")
resp, err := client.Do(req)
if err != nil panic(err)
defer resp.Body.Close()
fmt.Println("Status:", resp.Status)
}
For binary API in Go, use packages like github.com/go-routeros/routeros.
queues = api('/queue/simple/print', '?name': 'user1')
if queues:
api('/queue/simple/remove', '.id': queues[0]['.id'])
# Disable an interface
api('/interface/set',
'.id': 'ether2',
'disabled': 'yes'
)