我正在编写一个小型实用工具进行开发,以通过ssh同步文件。通常,我使用.bashrc文件中设置的ssh-agent轻松连接到我的开发服务器。我想在脚本中使用exec,但是每次我发出请求时,都调用ssh-agent听起来不太理想。
有没有一种方法可以执行一次代理代码,然后使其对我提出的所有后续ssh请求起作用?例如。生成类似于终端仿真器的shell进程,然后使用该进程执行命令,而不是使用每个命令调用新的shell。
我要这样做的原因是,我不想将密码存储在配置文件中。
答案 0 :(得分:1)
您可以创建一个ssh进程,然后使用相同的进程执行其他命令。这是一个如何将其用于bash的示例。我正在创建一个新的bash
shell,并执行命令ls -la
和exit
,您可以执行其他命令。
const cp = require("child_process")
class MyShell {
constructor(command) {
this._spawned = cp.spawn(command, {
stdio: ["pipe", "pipe", "inherit"],
})
}
execute(command, callback) {
this._spawned.stdin.write(command + "\n")
this._spawned.stdout.on("data", (chunk) => {
if (callback) {
callback(chunk.toString())
}
})
}
}
var myShell = new MyShell("bash")
myShell.execute("ls -la", (result) => {
console.log(result)
})
myShell.execute("exit")