There is no cPanel API call that starts or stops a service. There is one that restarts a service,
it is WHM API 1’s restartservice, it is plain HTTPS with a JSON response, and the whole
thing is four lines of Python:
import os, requests
r = requests.get(
"https://hostname.example.com:2087/json-api/restartservice",
params={"api.version": 1, "service": "httpd"},
headers={"Authorization": f"whm root:{os.environ['WHM_API_TOKEN']}"},
timeout=30,
)
An earlier version of this page taught something else entirely — an XML-RPC client, a
login() call, and a cpsrvd.start_service() method. None of those exist.
This rewrite explains how to tell, because the failure mode is instructive.
Table of Contents
Why the old code looked plausible and could never have worked
Start with the install line. pip install xmlrpc-client installs nothing:
$ for p in requests xmlrpclib xmlrpc xmlrpc-client definitely-fake-pkg-zzz999; do
printf '%-30s ' "$p"; curl -s -o /dev/null -w 'HTTP %{http_code}\n' "https://pypi.org/pypi/$p/json"
done
requests HTTP 200
xmlrpclib HTTP 200
xmlrpc HTTP 404
xmlrpc-client HTTP 404
definitely-fake-pkg-zzz999 HTTP 404
The last line is the control: a package name I invented returns the same 404 as
xmlrpc-client. (Check via the JSON API, not the project page — pypi.org serves a bot
challenge with status 200 to curl for every name, real or not.) The module the old page
wanted is already installed anyway:
$ python3 -c "import xmlrpc.client; print(xmlrpc.client.__file__)"
/Library/.../lib/python3.9/xmlrpc/client.py
Now the part that explains how a page like that gets published. This runs without raising anything:
>>> s = xmlrpc.client.ServerProxy('https://example.invalid:2087', allow_none=True)
>>> m = s.cpsrvd.start_service
>>> type(m).__name__
'_Method'
ServerProxy turns any attribute access into a remote method name. There is
no local validation, so invented method names look fine until something answers. Pointed at a stub
server on this machine that behaves like WHM’s JSON API, the code shows what it is really sending:
$ python3 -c "... s.login('user','password') ..."
login() -> ProtocolError: <ProtocolError for 127.0.0.1:18443/: 404 Not Found>
# what the stub server received:
POST /
Content-Type: text/xml
body: <?xml version='1.0'?><methodCall><methodName>login</methodName>...
An XML document POSTed to /, at a server that serves JSON from
/json-api/. That was never going to work on any version of cPanel.
What WHM actually gives you
Three functions, per cPanel’s API documentation:
restartservice— restarts one service. Parameters:service(required) andqueue_task(optional, defaults to 0). Requires the restart ACL.servicestatus— reports which services are enabled, installed, monitored and running. Requires the status ACL.configureservice— enables or disables a service and its monitoring. This is the closest thing to “stop”, and it is not the same thing: it is a persistent configuration change, not a transient one. cPanel’s docs warn specifically not to use it to disablecpsrvd.
Valid service names include httpd, mysql, exim,
named, sshd, crond, ftpd, imap,
pop, spamd and postgresql — so the old page’s
'httpd' was the one correct token in the whole snippet. Note also that this is WHM
territory: none of these exist in UAPI, and WHM API 1 cannot be called on cPanel’s ports 2082/2083.
A normal cPanel user cannot restart Apache. (UAPI does have
WebApp/start/stop/restart, but those control the user’s own
application process, not system daemons.)
Authentication: one correction to the common advice
Use an API token. Create it in WHM at Home » Development » Manage API Tokens, or with
the api_token_create function, and save it immediately — cPanel’s docs are explicit
that you cannot retrieve it again after leaving the page. The header format is
Authorization: whm username:token for WHM API 1 and
Authorization: cpanel username:token for UAPI. Tokens can carry an ACL list, an expiry,
and an IP allow-list, which a password cannot.
But it is worth being accurate about what changed, because “API tokens replaced password auth”
is repeated a lot and is not true. Basic authentication with an account password is still the only
declared security scheme in cPanel’s own OpenAPI description for both APIs, and still has a current
documentation page with working examples. cPanel recommends against it — “We recommend that
you use secure remote logins instead of username and password authentication when possible” — it has
not removed it. What is deprecated is the older access-hash mechanism, whose
get_remote_access_hash function is now labelled deprecated in favour of
api_token_list.
The TLS trap, demonstrated
cPanel’s published sample code disables certificate verification, because every sample connects
to 127.0.0.1, where the certificate is self-signed by design. That reasoning does not
survive the copy-paste to a remote hostname. Against a local stub with a self-signed certificate:
verify ON -> URLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
verify OFF -> 200 Waiting for httpd to restart...finished.
The second line is the point. With verification off, the client accepts any certificate,
which means it will happily hand your root API token to whatever answers on port 2087 — and that
token is a bearer credential with the privilege to restart services on your server. Connect by the
hostname the certificate is issued for and leave verification on. If your WHM genuinely has no valid
certificate, fix that (cPanel issues certificates for the whm service subdomain) rather
than turning off the check.
For comparison, the same stub rejects an unauthenticated request outright:
$ curl -s "https://.../json-api/restartservice?api.version=1&service=httpd"
{"metadata": {"result": 0, "reason": "Access denied"}} HTTP 403
$ curl -s -H 'Authorization: whm root:TOKEN' "https://.../json-api/restartservice?api.version=1&service=httpd"
{"data": {"output": "Waiting for httpd to restart...finished.\n", "service": "httpd"},
"metadata": {"command": "restartservice", "reason": "OK", "result": 1, "version": 1}} HTTP 200
A version you can use
import os, sys, requests
HOST = os.environ["WHM_HOST"] # the hostname on the certificate
USER = os.environ.get("WHM_USER", "root")
TOKEN = os.environ["WHM_API_TOKEN"] # never a literal in source
def whm(function, **params):
params.setdefault("api.version", 1)
r = requests.get(f"https://{HOST}:2087/json-api/{function}",
params=params,
headers={"Authorization": f"whm {USER}:{TOKEN}"},
timeout=30) # verify defaults to True - leave it
r.raise_for_status()
body = r.json()
if body.get("metadata", {}).get("result") != 1:
raise RuntimeError(f"{function}: {body.get('metadata', {}).get('reason')}")
return body.get("data", {})
if __name__ == "__main__":
print(whm("restartservice", service=sys.argv[1])["output"])
Three things the old script did not do. It checks
metadata.result — WHM returns HTTP 200 with result: 0 on a failure, so
status code alone is not enough. It never puts the token in a variable that gets printed. And it
lets requests verify the certificate, which is the default; the dangerous thing is the
verify=False you will be tempted to add the first time it errors.
I do not have a cPanel licence, so this was exercised against a local stub that returns the documented response shape, not against a real WHM. The endpoint, parameters, header format and ACL requirements come from cPanel’s API documentation, and the verify script for this page runs the offline half of it end to end.
Check this yourself. Every command and every block of output on this page is reproduced by /verify/python-start-shutdown-cpanel-host.sh. Download it and run it: it creates its own scratch files, prints one line per claim, cleans up after itself, and exits non-zero if any claim here turns out to be wrong. If it disagrees with this page, the page is wrong.