Skip to main content

Issue with Backup/list_backups Endpoint Returning Empty Data

Comments

8 comments

  • cPRex Jurassic Moderator

    Hey there! Can you post the full API call you are using that isn't working properly so I can see that?  Using the following API call on a server is working how I would expect on my end:

    uapi --user=username Backup list_backups
    0
  • Zubair Shaikh

    But I want to use api list backup using api not cli

    0
  • Zubair Shaikh

    I want to do generate the backup and check the backup status then download the back-up using remote server

    0
  • cPRex Jurassic Moderator

    Can you let me know the exact API call you're using that isn't working?

    0
  • Zubair Shaikh

    import requests
    import json
    import time
    from urllib.parse import urlencode

    # Disable SSL warnings
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    # cPanel API credentials
    CPANEL_HOST = "srv1.my-cloud-server.com"
    CPANEL_USERNAME = "fggffg"
    CPANEL_PASSWORD = "gfgfgfgfg"

    # API URLs
    BASE_URL = f"https://{CPANEL_HOST}:2083"
    API_URL = f"{BASE_URL}/execute/"
    TOKEN_URL = f"{BASE_URL}/login/?login_only=1"

    # Set a timeout for requests
    TIMEOUT = 30  # seconds

    def debug_print(message):
        print(f"[DEBUG] {message}")

    def get_access_token():
        debug_print("Attempting to get access token")
        data = {
            "user": CPANEL_USERNAME,
            "pass": CPANEL_PASSWORD
        }
        try:
            debug_print(f"Connecting to {TOKEN_URL}")
            response = requests.post(TOKEN_URL, data=data, verify=False, timeout=TIMEOUT)
            debug_print(f"Response status code: {response.status_code}")
            debug_print(f"Response headers: {response.headers}")
            debug_print(f"Response content: {response.text}")
            
            if response.status_code == 200:
                try:
                    token = response.json().get("security_token")
                    if token:
                        debug_print("Successfully obtained access token")
                        return token
                    else:
                        debug_print("Security token not found in response")
                        raise Exception("Security token not found in response")
                except json.JSONDecodeError:
                    debug_print("Failed to decode JSON response for access token")
                    raise
            else:
                debug_print(f"Failed to obtain access token. Status code: {response.status_code}")
                raise Exception("Failed to obtain access token")
        except requests.exceptions.RequestException as e:
            debug_print(f"Error connecting to the server: {str(e)}")
            raise

    def make_api_request(module, function, parameters=None):
        debug_print(f"Making API request: {module}/{function}")
        token = get_access_token()
        url = f"{API_URL}{module}/{function}"
        headers = {
            "Authorization": f"cpanel {CPANEL_USERNAME}:{token}"
        }
        try:
            debug_print(f"Sending request to: {url}")
            debug_print(f"Headers: {headers}")
            debug_print(f"Parameters: {parameters}")
            response = requests.get(url, headers=headers, params=parameters, verify=False, timeout=TIMEOUT)
            debug_print(f"Response status code: {response.status_code}")
            debug_print(f"Response headers: {response.headers}")
            debug_print(f"Response content: {response.text}")
            return response.json()
        except json.JSONDecodeError:
            debug_print(f"Failed to decode JSON response for {module}/{function}")
            return None
        except requests.exceptions.RequestException as e:
            debug_print(f"Error making API request: {str(e)}")
            return None

    def list_backups():
        debug_print("Listing available backups...")
        response = make_api_request("Backup", "list_backups")
        if response is None:
            debug_print("No response received from list_backups API")
            return None
        if "data" in response and isinstance(response["data"], list):
            backups = response["data"]
            if backups:
                latest_backup = max(backups, key=lambda x: x["time"])
                debug_print(f"Latest backup found: {latest_backup['filename']}")
                return latest_backup['filename']
            else:
                debug_print("No backups found.")
                return None
        else:
            debug_print("Unexpected response format")
            debug_print(f"Response: {response}")
            return None

    def download_backup(backup_file):
        debug_print(f"Initiating download for backup: {backup_file}")
        token = get_access_token()
        download_url = f"{BASE_URL}/cpsess{token}/download?filename={backup_file}&homedir=public_html&skipsession=1"
        
        try:
            debug_print(f"Sending download request to: {download_url}")
            response = requests.get(download_url, verify=False, stream=True, timeout=TIMEOUT)
            debug_print(f"Download response status code: {response.status_code}")
            
            if response.status_code == 200:
                with open(backup_file, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        f.write(chunk)
                debug_print(f"Backup downloaded successfully: {backup_file}")
                return True
            else:
                debug_print(f"Failed to download backup. Status code: {response.status_code}")
                debug_print(f"Response content: {response.text}")
                return False
        except requests.exceptions.RequestException as e:
            debug_print(f"Error downloading backup: {str(e)}")
            return False

    def main():
        try:
            debug_print("Starting backup download process")
            backup_file = list_backups()
            if backup_file:
                download_backup(backup_file)
            else:
                debug_print("No backup available to download")
        except Exception as e:
            debug_print(f"An error occurred: {str(e)}")

    if __name__ == "__main__":
        main()

    0
  • Zubair Shaikh

    y
    [DEBUG] Starting backup download process
    [DEBUG] Listing available backups...
    [DEBUG] Sending request to: https://srv1.my-cloud-server.com:2083/execute/Backup/list_backups
    [DEBUG] Headers: {'Authorization': 'Basic dG9vbHJhdmU6QW1pdDU5ODBA', 'Content-Type': 'application/json'}
    [DEBUG] Parameters: None
    [DEBUG] Response status code: 200
    [DEBUG] Response headers: {'Connection': 'close', 'Content-Type': 'application/json; charset="utf-8"', 'Date': 'Thu, 18 Jul 2024 05:39:09 GMT', 'Cache-Control': 'no-cache, no-store, must-revalidate, private, no-cache, no-store, must-revalidate, private, max-age=5184000, public', 'Pragma': 'no-cache', 'Expires': 'Mon, 16 Sep 2024 05:39:09 GMT', 'X-Frame-Options': 'SAMEORIGIN', 'X-Content-Type-Options': 'nosniff', 'Content-Length': '108'}
    [DEBUG] Response content: {"messages":null,"status":1,"metadata":{"transformed":1,"cnt":"0"},"errors":null,"data":[],"warnings":null}

    [DEBUG] No backups found.
    [DEBUG] No backup available to download

    0
  • Zubair Shaikh

    uapi --output=jsonpretty   --user=toolrave   Backup   list_backups
    {
       "apiversion" : 3,
       "func" : "list_backups",
       "module" : "Backup",
       "result" : {
          "data" : [],
          "errors" : null,
          "messages" : null,
          "metadata" : {
             "cnt" : "0",
             "transformed" : 1
          },
          "status" : 1,
          "warnings" : null
       }
    }

    0
  • cPRex Jurassic Moderator

    Thanks for the additional details.  That last code snippet you posted hows that there are no backups even though it completely properly as indicated by the "status : 1" section.

    You mentioned you have already created backups for the account.  Can you provide me more details specifically on how those backups were created and where they are stored?  That may be the key to this whole issue.

    0

Please sign in to leave a comment.