首先配置ubus的权限,在/usr/share/rpcd/acl.d/下生成一个文件,内容如下
{
"superuser": {
"description": "Super user access role",
"read": {
"ubus": {
"*": [ "*" ]
},
"uci": [ "*" ]
},
"write": {
"ubus": {
"*": [ "*" ]
},
"uci": [ "*" ]
}
}
}
这样就可以用root账号来访问ubus的rest api
python代码如下
class
Connection(
object):
def
__init__(
self,
server,
user,
passwd):
self.server =
"http://
{}
/ubus".format(server)
auth_response =
self._request(
"session",
"login",
username=user,
password=passwd)
assert
"ubus_rpc_session"
in auth_response
self._session_id = auth_response[
"ubus_rpc_session"]
@
property
def
session_id(
self):
if
not
hasattr(
self,
"_session_id"):
return
"00000000000000000000000000000000"
return
self._session_id
def
_request(
self,
subsytem,
method, **
params):
request = {
"jsonrpc":
"2.0",
"id":
1,
"method":
"call",
"params": [
self.session_id,
subsytem,
method,
params] }
response =
None
with requests.post(
self.server,
data=json.dumps(request))
as stream:
response = json.loads(stream.text)
if
not response
or
"error"
in response:
raise
str(response)
if response[
"result"][
0]==
0:
if
len(response[
"result"])>
1:
return response[
"result"][
1]
else:
return
"success"
else:
return
"error"
if
__name__ ==
"__main__":
if
len(sys.argv) <
4:
print(
"Usage:
{}
<OpenWrt_Host> <User> <Pass>]".format(sys.argv[
0]))
sys.exit(
1)
clients = []
connection = Connection(sys.argv[
1], sys.argv[
2], sys.argv[
3])
print(connection._request(
"uci",
"set",
config=
"wireless",
section=
"@wifi-iface[0]",
values={
"macfilter":
"deny"}))