idlers-agent/main.py
Swapnil 96e2328d5d
All checks were successful
buildbot/travis_bionic Build done.
buildbot/multibuild_parent Build done.
Added agent code
2024-06-03 12:12:38 +05:30

123 lines
3.2 KiB
Python

import os
import time
import json
import requests
import psutil
import tldextract
import dns.resolver
# get ram and disk in MB and GB respectively
def get_ram_and_disk():
ram = psutil.virtual_memory().total >> 20
disk = psutil.disk_usage('/').total >> 30
return ram, disk
def get_cpu_count():
return psutil.cpu_count()
def get_bandwidth():
return 2000
def get_hostname():
return os.uname().nodename
def get_public_ip():
try:
response = requests.get('https://api.ipify.org')
response.raise_for_status()
return response.text
except:
return '127.0.0.1'
def get_domain():
extracted = tldextract.extract(get_hostname())
return "{}.{}".format(extracted.domain, extracted.suffix)
def get_nameservers():
try:
answers = dns.resolver.resolve(get_domain(), 'NS')
return [str(rdata) for rdata in answers]
except Exception as e:
return []
def get_os():
return 27
# Create POST data
def create_post_data():
ram, disk = get_ram_and_disk()
nameservers = get_nameservers()
post_data = {
"server_type": 1,
"os_id": get_os(),
"provider_id": 10,
"location_id": 15,
"ssh_port": 22,
"ram": ram >> 10, # convert to GB
"ram_as_mb": ram, # in MB
"disk": disk, # in GB
"disk_as_gb": disk, # in GB
"cpu": get_cpu_count(),
"bandwidth": get_bandwidth(),
"was_promo": 1,
"active": 1,
"show_public": 0,
"owned_since": "2022-01-01",
"ram_type": "GB",
"disk_type": "GB",
"currency": "USD",
"price": 4,
"payment_term": 1,
"hostname": get_hostname(),
"next_due_date": "2022-02-01",
# Above ones are required fields, below are optional
"ns1": nameservers[0] if nameservers else "",
"ns2": nameservers[1] if len(nameservers) > 1 else "",
# "has_yabs": 0,
"ip1": get_public_ip(), # empty string or None gives 400 Bad Request
# "as_usd": 4,
# "usd_per_month": 4,
}
return post_data
def send_post_request():
# Get the API key and HOST from environment variables
api_key = os.getenv('API_KEY')
host = os.getenv('HOST')
if not api_key:
raise Exception('API_KEY not found in environment variables')
if not host:
raise Exception('HOST not found in environment variables')
# Create the headers for the request
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + api_key,
}
# Create the data for the post request
post_data = create_post_data()
payload = json.dumps(post_data)
# Send the POST request
try:
response = requests.post(host, headers=headers, data=payload)
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
print ("Something went wrong:",err)
else:
print(response.text)
if __name__ == '__main__':
send_post_request()