calog/examples/scripts/libraries/ssh.lua

57 lines
2.3 KiB
Lua

-- Showcase the calog ssh/sftp library as a safe-to-run, documented template:
-- connect + password auth, run a remote command and print its stdout, then a
-- round-trip through SFTP (upload a small payload with sftpPut, read it back
-- with sftpGet, and verify it matches). The entire flow is wrapped in pcall,
-- so with no reachable server it prints one clear hint and exits cleanly.
-- Run: bin/calog examples/scripts/libraries/ssh.lua
-- EDIT THESE: point them at a real SSH server you control before running.
-- The placeholder host below deliberately does not resolve, so the example is
-- safe to run as-is: it prints a hint and exits 0 instead of touching a server.
local HOST = "ssh.example.invalid"
local USER = "youruser"
local PASS = "yourpass"
local PORT = 22
-- A remote path we may create and delete; keep it under /tmp so cleanup is safe.
local REMOTE_PATH = "/tmp/calog_ssh_example.txt"
local PAYLOAD = "hello from the calog ssh example\n"
-- Everything network-facing lives here so a single pcall can catch a missing
-- server, refused connection, or auth failure without crashing the script.
local function demo()
local session = sshConnect(HOST, PORT)
calogPrint("connected to", HOST .. ":" .. PORT)
if not sshAuthPassword(session, USER, PASS) then
sshClose(session)
error("password authentication was rejected for user " .. USER)
end
calogPrint("authenticated as", USER)
-- Run a command remotely and show its captured output.
local run = sshExec(session, "uname -a")
calogPrint("remote uname:", run.stdout)
calogPrint("exit code:", run.exitCode)
-- SFTP round-trip: upload the payload, read it back, and compare.
sftpPut(session, REMOTE_PATH, PAYLOAD)
calogPrint("uploaded", #PAYLOAD, "bytes to", REMOTE_PATH)
local fetched = sftpGet(session, REMOTE_PATH)
calogPrint("downloaded", #fetched, "bytes back")
calogPrint("round-trip matches:", fetched == PAYLOAD)
-- Tidy up the remote file, then close the session.
sftpRemove(session, REMOTE_PATH)
sshClose(session)
calogPrint("session closed")
end
local ok, err = pcall(demo)
if not ok then
calogPrint("ssh example: set HOST/USER/PASS and point at a real SSH server")
calogPrint(" (" .. tostring(err) .. ")")
end
calogExit(0)