node.js - 在使用 Node 的子进程中使用 sudo 命令

标签 node.js linux ubuntu child-process

我正在尝试将捆绑目录复制到远程服务器的根目录中。我尝试使用 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/

相关文章:

node.js - TypeScript 找不到 @types 中的类型

node.js - 链接 Q.ninvoke 时出现类型错误

linux - cd 在这条路径上不起作用。有任何想法吗?

linux - 具有过程的二进制信号量的通用模板

linux - 在类 Unix 操作系统上重新映射系统范围的 key

java - 如何在没有任何端口的情况下直接使用 url 访问我的 Spring Boot Web 应用程序?

node.js - SequelizeJS - 为什么我的实例重新加载失败, "TypeError: Cannot read property ' dataValues' of null”

ajax - Node.js + Express : Upload a file without reloading page

mysql - 在 Ubuntu linux 上构建 C 项目出现错误 'mysql/mysql.h no such file'

ubuntu - 无法以网络用户身份运行 oowriter