This commit is contained in:
smolkik_adm
2026-09-03 02:55:09 +00:00
parent d4b73b3620
commit 602c7e5a78

View File

@@ -1,34 +1,60 @@
import requests
import urllib3
from getpass import getpass
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# ---
BASE_URL = "https://nameserver:9877"
COOKIE_STRING = ""
def authenticate(username, password):
auth_url = f"{BASE_URL}/idp/token"
auth_payload = {
"username": username,
"password": password,
"grant_type": "password",
}
try:
auth_response = requests.post(
auth_url,
data=auth_payload,
headers={"Content-Type": "application/x-www-form-urlencoded"},
proxies={"http": None, "https": None},
verify=False,
)
auth_response.raise_for_status()
auth_data = auth_response.json()
if "token_type" not in auth_data or "access_token" not in auth_data:
print("\033[91mОшибка: в ответе отсутствует токен\033[0m")
return None
return {
"Content-Type": "application/json",
"Authorization": f"{auth_data['token_type']} {auth_data['access_token']}",
}
except requests.exceptions.RequestException as e:
print(f"\033[91mОшибка аутентификации: {e}\033[0m")
return None
def main():
username = input("Введите имя пользователя: ")
password = getpass("Введите пароль: ")
if not username or not password:
print("\033[91mНе введён User или Password\033[0m")
return
headers = authenticate(username, password)
if not headers:
return
try:
# Формируем заголовки запроса, притворяясь авторизованным браузером
headers = {
"Cookie": COOKIE_STRING,
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
# Делаем прямой запрос к Resource Manager API
print("📊 Сбор информации об агентах через сессию браузера...")
print("📊 Сбор информации об агентах...")
resources_url = f"{BASE_URL}/api/resource_manager/v1/agents"
response = requests.get(resources_url, headers=headers, verify=False)
# Проверяем успешность
if response.status_code == 401:
print("❌ Ошибка 401: Сессия устарела или Cookie скопированы неверно. Обновите страницу в браузере и скопируйте Cookie заново.")
print("❌ Ошибка 401: токен недействителен или истёк.")
return
elif response.status_code != 200:
print(f"❌ Сервер вернул ошибку HTTP {response.status_code}")
@@ -38,7 +64,6 @@ def main():
data = response.json()
agents = []
# Фильтруем агенты по нужным типам
for item in data.get("items", []):
agent_type = item.get("type")
if agent_type in ["agent"]:
@@ -47,10 +72,9 @@ def main():
"type": agent_type,
"online": item.get("communication", {}).get("online", False),
"os": item.get("details", {}).get("os", {}).get("name", "N/A"),
"ip": ", ".join(item.get("details", {}).get("ipAddresses", ["N/A"]))
"ip": ", ".join(item.get("details", {}).get("ipAddresses", ["N/A"])),
})
# Выводим результат в терминал PowerShell
print(f"\nВсего найдено агентов/устройств: {len(agents)}\n")
print(f"{'Имя устройства':<40} | {'Тип':<15} | {'Статус':<8} | {'ОС':<30} | {'IP-адреса'}")
print("-" * 120)
@@ -67,5 +91,6 @@ def main():
except Exception as e:
print(f"\n❌ Ошибка выполнения скрипта: {e}")
if __name__ == "__main__":
main()
main()