Way to pass a http-command to a PC. Used here to shutdown a PC
Security is obviously not a concern in this solution.
Please share your improvements. Autodetect for Linux / Windows would be nice.
Security is obviously not a concern in this solution.
Please share your improvements. Autodetect for Linux / Windows would be nice.
Code:
local http = require("socket.http")
local url = require("socket.url")
local socket = require("socket")
--
-- This function does remote function invocation like:
-- http://username:password@127.0.0.1:8080/action?name=alarm
-- It is assumed, that username and password are present in the url;
-- another assumption, that on the windows machine there will be
-- installed software like "shutter", see http://www.den4b.com/?x=products
--
-- if wait_delay is defined positive, then after wait_delay seconds it
-- will do "TCP knock" to check if the remote host is alive. Is if is
-- still alive, then notification email will be sent.
--
function shutdown_regular(command_url, wait_delay)
local admin_email = 'mrx@openmailbox.org'
-- tcp knock help function
function tcp_knock(ip, port)
local tcp = assert(socket.tcp())
tcp:settimeout(10)
local success = tcp:connect(ip, port)
print("tcp knock to " .. ip .. " is " .. (success and "success" or "fail"))
return success
end
-- prepare data
local parsed_url = url.parse(command_url)
local host = parsed_url.host
local port = parsed_url.port or 80
-- invoke command url
http.TIMEOUT = 10
print(command_url)
local body, code = http.request{ url = command_url }
assert(body, code)
print("status = " .. code)
-- success invocation check
if (code ~= 200) then
local subject = "Remote command invocation failed on " .. host
local body = "Please, pay attention the host " .. host .. " returned status code = " .. code .. "\n"
body = body .. "the following command url: " .. command_url .. "\n"
mail(admin_email, subject, body)
return
end
wait_delay = tonumber(wait_delay)
if ( wait_delay and (wait_delay > 0) ) then
os.sleep(wait_delay)
local success = tcp_knock(host, port)
if ( not succeess ) then
local subject = "Remote command invocation failed on " .. host
local body = "Please, pay attention the host " .. host .. " is still alive after invocation \n"
body = body .. "the follwong command url: " .. command_url .. "\n"
mail(admin_email, subject, body)
end
end
end
-- uncomment the following lines to perform command-line test from linux
--[[
function mail(to, subject, body)
print("mail function simulation. to = " .. to .. ", subject = " .. subject .. "\n" .. body)
end
function os.sleep(seconds)
print("os.sleep simulation for " .. seconds .. " seconds")
end
shutdown_regular(arg[1], arg[2])
--]]