我正在尝试将捆绑目录复制到远程服务器的根目录中。我尝试使用 node 来执行此操作,到目前为止,我实现了将 tar 内容通过管道传输到服务器并对其进行解压缩。但是,当我尝试将目录移动到根文件夹时,它需要 sudo
访问权限,但我找不到执行此操作的方法。我为伪终端尝试了 -t
选项,但我想它可以从 shell 运行。这是我到目前为止所做的,非常感谢任何帮助:
const path = require("path");
const exec = require('child_process').exec;
var absolutePath = path.resolve(__dirname, "../");
const allCommands = [];
/*
*
*
* 1-) cd to the root folder of the app
* 2-) tar dist folder and pipe the result to the ssh connection
* 3-) connect to server with ssh
* 4-) try to create dist and old_dists folder, if not existing they will be created otherwise they will give an error and rest of the script will continue running
* 5-) cp contents of dist folder to old_dists/dist_$(dateofmoment) folder so if something is wrong somehow you have an backup of the existing config
* 6-) untar the piped tar content into dist folder, untar only files under the first parent directory --strip-components=1 flag, if it was 2 it will dive 2 level from the root folder
*
*
*/
allCommands.push("cd " + absolutePath);
allCommands.push("tar -czvP dist | ssh hostnameofmyserver 'mkdir dist ; mkdir old_dists; cp -R dist/ old_dists/dist_$(date +%Y%m%d_%H%M%S) && tar -xzvP -C dist --strip-components=1'");
//I would like to untar the incoming file into /etc/myapp for example rather than my home directory, this requires sudo and don't know how to handle it
exec(allCommands.join(" && "),
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
此外,在多个用户可以部署应用程序的 ubuntu 服务器中存储 Web 应用程序文件夹的最佳位置是什么,让目录的所有者成为 root
用户是一个好习惯,还是只是不这样做没关系吗?
最佳答案
如 man page for ssh 中所述,您可以指定多个 -t
参数来强制分配 pty,即使 OpenSSH 客户端的标准输入不是 tty(当您在 Node 中生成子进程时默认情况下它不会是)。
当您在 .stdout
流上看到 sudo 提示时,您应该能够从那里简单地将密码写入子进程的 .stdin
流。
半相关说明,如果您想要对 ssh 连接进行更多(编程)控制,或者您不想启动子进程,可以使用 ssh2
模块。如果您愿意,您甚至可以在 Node 内进行压缩,因为 npm 上也有压缩包模块。
关于node.js - 在使用 Node 的子进程中使用 sudo 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40576879/