Art-of-WiFi / UniFi-API-client

A PHP API client class to interact with Ubiquiti's UniFi Controller API
MIT License
1.13k stars 223 forks source link

enable/disable port forwarding #62

Closed vespino closed 4 years ago

vespino commented 4 years ago

I have found it's possible to grab a list of port forwardings, but is it possible to enable/disable a port forwarding rule using the API?

malle-pietje commented 4 years ago

There aren’t specific functions in the client for this (yet), but you can achieve it by using the custom method. I can check to see what that would roughly look like.

malle-pietje commented 4 years ago

When using the custom_api_request() method it should be called like so:

custom_api_request('/api/s/YOUR_SITE_ID/rest/portforward', 'POST', $payload, 'array');

Here $payload must be a PHP associative array that is structured similar to the output from list_portforwarding():

    {
        "_id": "5ebd0c38a999c65ac2162e9e",
        "enabled": true,
        "pfwd_interface": "wan",
        "name": "test rule for 2222",
        "dst_port": "2222",
        "fwd": "192.168.0.10",
        "fwd_port": "2221",
        "log": true,
        "src": "any",
        "proto": "tcp_udp",
        "site_id": "558c44fee4b000d0b32a8bbb"
    }
malle-pietje commented 4 years ago

So if you wish to simply enable/disable one rule temporarily, fetch all rules using list_portforwarding(), extract the required rule, modify the enabled attribute and push the single rule back using the above example.

vespino commented 4 years ago

@malle-pietje thanks again for your response. It seems to add new rules instead of updating the existing rule, so I'll probably have to delete a rule first then insert the new (updated) rule.

Also the post must be made to the following path: /api/s/default/rest/portforward/[site id]

vespino commented 4 years ago

Found it: $unifi_connection->custom_api_request('/api/s/default/rest/portforward/['_id'], 'PUT', $payload, 'array');

malle-pietje commented 4 years ago

Ah OK, I see I forget to test an update of a rule, my example is for the creation of a rule. It must indeed be a PUT and the correct URL structure is:

/api/s/default/rest/portforward/[**rule_id**]

This assumes you are working with the default site and rule_id is the value for _id from the rule you are updating.

malle-pietje commented 4 years ago

You beat me to it😉

vespino commented 4 years ago

Thanks for pointing me to this method, it will probably open up a lot of possibilities!

malle-pietje commented 4 years ago

It does; I added it to allow users to go ahead by themselves without having to wait for me or someone else to push an update for a new specific function/route.