ssh - 通过SSH与文件io操作进行Lua脚本

标签 ssh lua

我正在尝试远程运行脚本(远程是服务器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()从脚本中返回值,以使本地脚本能够实际使用。

最佳答案

因为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文件夹不存在,权限不足或其他原因引起的;错误消息应将您指向正确的方向。

关于ssh - 通过SSH与文件io操作进行Lua脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31758534/

相关文章:

linux - 无法打开授权,权限被拒绝

git 错误 "unable to look up current user in the passwd file: no such user"- 这是什么意思?

linux - 无法设置无密码登录到 localhost 以及使用密码 ssh 到 localhost

sql - 将sql行id传递给corona中的tableview

lua - 关于lua corountine的resume和yield函数的困惑

math - LUA中的正态分布曲线和随机数

mysql - 使用 Liquibase (Docker) 连接到 SSH 隧道数据库

c++ - 可以将 Lua 转换为 spir-v 吗?

lua - 始终在最上面的窗口并保持焦点,在 AwesomeWM 上

linux - 使用 SSH 在桌面上打开应用程序