我正在尝试远程运行脚本(远程是服务器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操作?
此外,将值从远程脚本返回到本地主机的最佳方法是什么?我通过调用print()从我的脚本返回值,以便为我的本地脚本提供实际使用的东西。
答案 0 :(得分:1)
您收到此错误,因为io.open
调用返回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
文件夹,权限不足或其他原因造成的;错误信息应该指向正确的方向。