gpt4 book ai didi

node.js - 如何使用nodejs从远程服务器复制带有空格和utf8的文件

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:44 24 4
gpt4 key购买 nike

问题

我正在尝试构建一个 Node 应用程序,它将本地目录与远程目录进行比较,然后将所有新文件从远程目录复制到本地目录。不幸的是,许多文件是用户生成的内容,并且它们包含空格字符。我当前的实现似乎没有正确转义文件名字符串。 如何将这些文件复制到我的本地环境?

当前实现:

// ...
function copyRemoteFile(remoteFile, server, localDir) {
exec = require('child_process').exec;
remoteFile = remoteFile.replace(/ /g, '\\\\ ');
exec('scp ' + server + ':/path/to/files/' + remoteFile + ' ' localDir, function(error, stdout, stderr) {
console.log(error, stdout, stderr);
});
});
// ...

电流输出

对于此输入:

copyRemoteFile('Screen Shot 2013-12-04 at 1_00_13 PM.png', 'server', '.');

我得到这个输出:

{ [Error: Command failed: scp: /path/to/files/Screen: No > such file or directory cp: Shot\: No such file or directory cp: 2013-12-04\: No such file or directory cp: at\: No such file or directory cp: 1_00_13\: No such file or directory cp: PM.png: No such file or directory ] killed: false, code: 1, signal: null } '' 'scp: /path/to/files/Screen: No such file or
directory\ncp: Shot\: No such file or directory\ncp: 2013-12-04\: No such file or directory\ncp: at\: No such file or directory\ncp: 1_00_13\: No such file or directory\ncp: PM.png: No such file or directory\n'

最佳答案

npm install scp

scp.get({
file: '~/file.txt', // remote file to grab
user: 'username', // username to authenticate as on remote system
host: 'myServer', // remote host to transfer from, set up in your ~/.ssh/config
port: '22', // remote port, optional, defaults to '22'
path: '~' // local path to save to (this would result in a ~/file.txt on the local machine)
});

此处的文档:https://github.com/ecto/node-scp

源代码:https://github.com/ecto/node-scp/blob/master/scp.js

<小时/>

linux命令中的空格必须加引号:

copyRemoteFile('"Screen Shot 2013-12-04 at 1_00_13 PM.png"', 'server', '.');

如果您通过Web服务器调用exec linux命令,用户可能会使用特殊文件名来攻击您的服务器,您需要引用参数

关于node.js - 如何使用nodejs从远程服务器复制带有空格和utf8的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20578516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com