Lua 通过 SSH 执行文件 io 操作的脚本

Lua script via SSH with file io operations

我正在尝试 运行 远程脚本(远程是服务器 B)。当我 运行 服务器 A 上的本地脚本时,我得到了预期的结果。当我 运行 通过 SSH 从服务器 A 到服务器 B 的脚本时,出现以下错误:

/usr/bin/ssh admin@server.domain.com "lua/rpi.init" 
lua: lua/rpi.init:8: attempt to index upvalue 'logFile' (a nil value) stack traceback:
        lua/rpi.init:8: in function 'logMsg'
        lua/rpi.init:47: in main chunk

#!/usr/bin/env lua
local f = assert(io.popen("sudo netstat -a | grep ^tcp[^6] | grep LISTEN | grep [^0-9]22[0-9][0-9]", 'r'))
local ports22 = {}
local logFile

function logMsg(msg)
        logFile = io.open("logs/pi.init.log", "a+")
        logFile:write(os.date("%b %d %Y %X ") .. tostring(msg) .. "\n")
        logFile:close()
end

function getPorts22()
logMsg("Getting available ports...")
while true do
        line = f:read()
        if line == nil then break end
        port = string.sub(line, 40, 44)
        table.insert(ports22, port)
end
f:close()
table.sort(ports22)
end

function getNextOpenPort22()
        local openPort = 2222
        if #ports22 == 0 then
                logMsg("Returning port :" .. openPort)
                return openPort
        end
        for i=1, #ports22 + 1 do
                if tonumber(ports22[i]) == openPort then
                        openPort = openPort + 1
                else
                        logMsg("Returning port: " .. openPort)
                        return openPort
                end
        end

end


function printPorts()
        msg = table.concat(ports22, ", ")
        logMsg("Found ports in use: " .. tostring(msg))
end

logMsg("Script called to run.")
getPorts22()
printPorts()
print(getNextOpenPort22())

是否可以通过 SSH(bash、lua 或其他方式)运行 脚本并让它们在远程机器上执行 io 操作?

此外,从远程脚本到本地主机的 return 值的最佳方法是什么?我 return 通过调用 print() 从我的脚本中获取值,以便为我的本地脚本提供实际使用的东西。

您收到此错误是因为 io.open 调用 returns 一个 nil 值和一条错误消息。您可能需要将此行 logFile = io.open("logs/pi.init.log", "a+") 更改为如下内容:

local logFile, err = io.open("logs/pi.init.log", "a+")
if not logFile then error(err, 2) end

这将在 io.open 调用不成功时打印错误消息。在你的情况下,它可能是由不存在的 logs 文件夹、权限不足或其他原因引起的;错误消息应该为您指明正确的方向。