sal/examples/network/network_connectivity.rhai
kristof ba9103685f
Some checks failed
Rhai Tests / Run Rhai Tests (push) Has been cancelled
...
2025-06-16 07:53:03 +02:00

83 lines
2.2 KiB
Plaintext

// Example of using the network modules in SAL
// Shows TCP port checking, HTTP URL validation, and SSH command execution
// Import system module for display
import "os" as os;
// Function to print section header
fn section(title) {
print("\n");
print("==== " + title + " ====");
print("\n");
}
// TCP connectivity checks
section("TCP Connectivity");
// Create a TCP connector
let tcp = sal::net::TcpConnector::new();
// Check if a port is open
let host = "localhost";
let port = 22;
print(`Checking if port ${port} is open on ${host}...`);
let is_open = tcp.check_port(host, port);
print(`Port ${port} is ${is_open ? "open" : "closed"}`);
// Check multiple ports
let ports = [22, 80, 443];
print(`Checking multiple ports on ${host}...`);
let port_results = tcp.check_ports(host, ports);
for result in port_results {
print(`Port ${result.0} is ${result.1 ? "open" : "closed"}`);
}
// HTTP connectivity checks
section("HTTP Connectivity");
// Create an HTTP connector
let http = sal::net::HttpConnector::new();
// Check if a URL is reachable
let url = "https://www.example.com";
print(`Checking if ${url} is reachable...`);
let is_reachable = http.check_url(url);
print(`${url} is ${is_reachable ? "reachable" : "unreachable"}`);
// Check the status code of a URL
print(`Checking status code of ${url}...`);
let status = http.check_status(url);
if status {
print(`Status code: ${status.unwrap()}`);
} else {
print("Failed to get status code");
}
// Only attempt SSH if port 22 is open
if is_open {
// SSH connectivity checks
section("SSH Connectivity");
// Create an SSH connection to localhost (if SSH server is running)
print("Attempting to connect to SSH server on localhost...");
// Using the builder pattern
let ssh = sal::net::SshConnectionBuilder::new()
.host("localhost")
.port(22)
.user(os::get_env("USER") || "root")
.build();
// Execute a simple command
print("Executing 'uname -a' command...");
let result = ssh.execute("uname -a");
if result.0 == 0 {
print("Command output:");
print(result.1);
} else {
print(`Command failed with exit code: ${result.0}`);
print(result.1);
}
}
print("\nNetwork connectivity checks completed.");