Skip to content

Instantly share code, notes, and snippets.

@chadbrewbaker
Created December 29, 2024 01:01
Show Gist options
  • Save chadbrewbaker/44e8f343473cd310c87cbcb481a15b01 to your computer and use it in GitHub Desktop.
Save chadbrewbaker/44e8f343473cd310c87cbcb481a15b01 to your computer and use it in GitHub Desktop.
Exploring ChatGPT 4o wasm32 runtime
# Remember: The environment can be both x86_64 Linux, or https://github.com/pyodide/pyodide wasm32 with missing modules like subprocess.
import platform
import sys
import os
import socket
from datetime import datetime
import pkgutil
import urllib.request
import logging
import ctypes
import js # Import the JavaScript module to interact with the environment
import asyncio
logging.basicConfig(level=logging.DEBUG)
# Lets use ctypes to gather system information
def print_ctypes_info():
print("Gathering system information using ctypes...")
try:
libc = ctypes.CDLL(None) # Load standard C library
# List all sysconf variables with names
print("Listing all sysconf variables...")
sysconf_values = {}
sysconf_name_map = {v: k for k, v in os.sysconf_names.items()} # Reverse mapping
output = [] # To append results into a single string
for i in range(0, 200): # Assuming typical range for sysconf values
try:
value = libc.sysconf(i)
if value != -1:
sysconf_values[i] = value
except Exception:
pass
for key, value in sysconf_values.items():
name = sysconf_name_map.get(key, f"Unknown ({key})")
output.append(f"sysconf[{name}] = {value}")
# Print all results at once
print("\n".join(output))
# Example: Getting cache line size on Linux
if hasattr(libc, "sysconf"):
_SC_LEVEL1_DCACHE_LINESIZE = os.sysconf_names.get("SC_LEVEL1_DCACHE_LINESIZE", 190)
cache_line_size = libc.sysconf(_SC_LEVEL1_DCACHE_LINESIZE)
print(f"L1 Cache Line Size: {cache_line_size} bytes")
else:
print("Cache line size information not available on this platform.")
except Exception as e:
print(f"Error using ctypes to gather system information: {e}")
# Function to list shared libraries
def list_shared_libraries():
print("Listing all shared libraries in the ctypes search path...")
shared_libraries = set()
# Check common library directories
library_dirs = ["/", "/lib", "/usr/lib", "/usr/local/lib"] + os.environ.get("LD_LIBRARY_PATH", "").split(":")
library_dirs = [d for d in library_dirs if os.path.isdir(d)] # Filter existing directories
try:
for lib_dir in library_dirs:
for entry in os.scandir(lib_dir):
if entry.is_file():
shared_libraries.add(entry.name)
except Exception as e:
print(f"Error scanning library directories: {e}")
print("Shared libraries found:")
for lib in sorted(shared_libraries):
print(lib)
# Function to retrieve system information using js module
def get_js_system_info():
print("Retrieving system information using JavaScript module...")
try:
navigator = js.eval("navigator")
system_info = {
"UserAgent": navigator.userAgent,
"Platform": navigator.platform,
"Language": navigator.language,
"Online": navigator.onLine,
}
for key, value in system_info.items():
print(f"{key}: {value}")
except Exception as e:
print(f"Error retrieving system information using js module: {e}")
# Function to retrieve network information using js module
def get_js_network_info():
print("Retrieving network information using JavaScript module...")
try:
connection = js.eval("navigator.connection || navigator.mozConnection || navigator.webkitConnection")
if connection:
network_info = {
"EffectiveType": getattr(connection, "effectiveType", "Not available"),
"Downlink": getattr(connection, "downlink", "Not available"),
"RTT": getattr(connection, "rtt", "Not available"),
"SaveData": getattr(connection, "saveData", "Not available"),
}
for key, value in network_info.items():
print(f"{key}: {value}")
else:
print("Network connection information not available.")
except Exception as e:
print(f"Error retrieving network information using js module: {e}")
# Function to test DNS resolution using js module
async def test_js_dns_resolution(domain):
print(f"Testing DNS resolution for {domain} using JavaScript module...")
try:
js_code = f"""
(async function() {{
try {{
const response = await fetch('https://{domain}');
if (response.ok) {{
return 'Success: Resolved and connected to {domain}';
}} else {{
return `Failure: Status ${{response.status}}`;
}}
}} catch (error) {{
return `Error: ${{error.message}}`;
}}
}})();
"""
promise = js.eval(js_code)
result = await promise
print(f"Result: {result}")
except Exception as e:
print(f"Error testing DNS resolution using JavaScript module: {e}")
# Print environment variables
print("Environment Variables:")
env_variables = "\n".join([f"{key}={value}" for key, value in os.environ.items()])
print(env_variables)
# Information about the operating system
print("\nOperating System Information:")
print(f"Unnamed Platform: {os.uname()}" if hasattr(os, "uname") else "Not available")
# Additional useful functions
print("\nAdditional Info:")
print(f"Home Directory: {os.path.expanduser('~')}")
print(f"Current User: {os.getlogin() if hasattr(os, 'getlogin') else 'Not available on this platform'}")
# List all available modules
modules = list(sys.modules.keys())
print("Available Modules:")
modules_string = "\n".join(sorted(modules))
print(modules_string)
# Step 5: Network information
def get_network_info():
print("Gathering network information...")
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
interface_info = {
"Placeholder": "Network interface information not available."
}
return {"Hostname": hostname, "IP Address": ip_address, "Interfaces": interface_info}
# Step 6: Running processes
def get_running_processes():
print("Gathering running processes information...")
processes = [
{"Placeholder": "Process information not available."}
]
return processes
# Step 7: Python environment details
def get_python_environment():
print("Python environment details collection skipped.")
return "Placeholder: Python environment details not collected."
# Main function
async def main():
print("Starting system diagnostics...")
# Print system information using ctypes
print_ctypes_info()
# Retrieve system information using js module
get_js_system_info()
# Retrieve network information using js module
get_js_network_info()
# Test DNS resolution using js module
await test_js_dns_resolution("example.com")
# List shared libraries
list_shared_libraries()
network_info = get_network_info()
print("Network Information:", network_info)
running_processes = get_running_processes()
print("Running Processes:", running_processes[:10], "... (truncated)")
python_environment = get_python_environment()
print("Python Environment:", python_environment)
print("System diagnostics complete.")
# Run the async main function
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment