Refactor auto-boot-ollama-host script into modular structure with separate configuration, network, SSH, and service management modules for improved maintainability and readability
This commit is contained in:
69
scripts/ssh.lua
Normal file
69
scripts/ssh.lua
Normal file
@@ -0,0 +1,69 @@
|
||||
-- SSH utilities module for auto-boot-ollama-host
|
||||
-- Provides SSH command execution functionality
|
||||
|
||||
local utils = require("utils")
|
||||
|
||||
local ssh_module = {}
|
||||
|
||||
-- Execute a remote command over SSH
|
||||
-- Signature: ssh(command, user, host, port, identity_file)
|
||||
function ssh_module.execute(command, user, host, port, identity_file)
|
||||
-- Basic validation and defaults
|
||||
user = tostring(user or "")
|
||||
host = tostring(host or "")
|
||||
port = tonumber(port or 22) or 22
|
||||
identity_file = tostring(identity_file or "")
|
||||
|
||||
-- Quote a string for safe single-quoted POSIX shell context
|
||||
local function sq(s)
|
||||
-- Replace ' with: '\'' (close, escape quote, reopen)
|
||||
return "'" .. tostring(s):gsub("'", "'\\''") .. "'"
|
||||
end
|
||||
|
||||
-- Build base ssh command (run locally)
|
||||
-- -oBatchMode to avoid interactive prompts
|
||||
-- -oConnectTimeout for faster failure
|
||||
-- -oStrictHostKeyChecking uses known_hosts; adjust if needed
|
||||
local dest = (user ~= "" and (user .. "@" .. host) or host)
|
||||
local pieces = {
|
||||
"ssh",
|
||||
"-p", tostring(port),
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", "ConnectTimeout=30",
|
||||
"-o", "ServerAliveInterval=5",
|
||||
"-o", "ServerAliveCountMax=1",
|
||||
"-o", "UserKnownHostsFile=/root/.ssh/known_hosts",
|
||||
"-o", "StrictHostKeyChecking=yes",
|
||||
}
|
||||
|
||||
if identity_file ~= "" then
|
||||
table.insert(pieces, "-i")
|
||||
table.insert(pieces, identity_file)
|
||||
end
|
||||
table.insert(pieces, dest)
|
||||
|
||||
-- Pass remote command as provided; caller is responsible for proper quoting
|
||||
table.insert(pieces, "--")
|
||||
table.insert(pieces, command)
|
||||
|
||||
-- Join with spaces for os.execute
|
||||
local function join(args)
|
||||
-- We only quote the remote command explicitly. Other args are simple tokens.
|
||||
return table.concat(args, " ")
|
||||
end
|
||||
|
||||
local full = join(pieces)
|
||||
utils.log("SSH exec: " .. full)
|
||||
|
||||
local ok, reason, code = os.execute(full)
|
||||
if ok == true or ok == 0 then
|
||||
utils.log("SSH command completed successfully")
|
||||
return true
|
||||
else
|
||||
local msg = string.format("SSH failed: reason=%s code=%s", tostring(reason), tostring(code))
|
||||
utils.log(msg)
|
||||
return false, msg
|
||||
end
|
||||
end
|
||||
|
||||
return ssh_module
|
||||
Reference in New Issue
Block a user