1

我写了一个测试scp传输的代码。这是代码。

var async = require('async'),
    nexpect = require('nexpect'),
    arg = {
    'host' : '192.168.0.3',
    'username' : 'root',
    'password' : 'rootpwd',
    'path' : '~'
    },
    file_list = ['a.txt', 'b.txt', 'c.txt'];

function scpFileTransfer(arg, callback) {
    nexpect.spawn('scp ' + arg.file + ' ' + arg.username + '@' + arg.host + ':' + arg.path, { stream: 'stderr' })
        .wait(/password/)
        .sendline(arg.password)
        .run(function (err) {
            if(err) console.log(err);
            else console.log('from ' + arg.file + ' to ' + arg.username + '@' + arg.host + ':' + arg.path + ' success!');
            callback();
        }
    );
}

async.eachSeries(file_list, function(item, callback) {
    arg.file = item;
    scpFileTransfer(arg, function () {
        callback();
    });
}, function (err) {
    if(err) console.trace(err);
    else console.log('success');
});

我期望这样的输出,

from a.txt to root@192.168.0.3:~ success!
from b.txt to root@192.168.0.3:~ success!
from c.txt to root@192.168.0.3:~ success! 

但输出与我的预期不同。我的 node.js 模块正在等待命令行输入。如何在没有命令行输入的情况下运行我的代码?

4

1 回答 1

0

我自己解决了这个问题。

在 node.js 中使用 scp 传输,需要重定向 stdout 流。

所以,我尝试使用 fs.readSync 函数重定向 /dev/stdout。

但是我的程序因“未知错误”而死。

此代码是新的 scpFileTransfer 函数,使用“期望”程序既不期望模块也不重定向。

function scpFileTransfer(arg, callback) {
    var buf = new Buffer(256),
        len = 0,
        scp;
    len += buf.write(   'set timeout -1\n' +
                        'spawn scp ' + arg.file + ' ' + arg.username + '@' + arg.host + ':' + arg.path + '\n' +
                        'expect -exact "password: "\n' +
                        'send -- "' + arg.password + '\r"\n' +
                        'expect {\$\s*} { interact }\n');
    fs.writeFileSync('./.scp_login.exp', buf.toString('utf8', 0, len));

    scp = spawn('expect', ['-f', '.scp_login.exp']);
    scp.stdout.on('data', function (data) {
        console.log(data.toString('utf8', 0, len));
    });
    scp.stderr.on('data', function (data) {
        console.log('stderr: ' + data);
    });
    scp.on('exit', function (code) {
        fs.unlink('./.scp_login.exp', function (err) {
            if(err) throw err;
        });
        callback();
    });
}

如果您在您的环境中运行此代码,您应该检查是否安装了 'expect' 程序。

如果没有,您可以通过以下命令安装。


Ubuntu - sudo apt-get install 期望

CentOS - 百胜安装期望

Mac OS X -(已安装在操作系统中。)


谢谢。

于 2014-07-16T05:19:55.767 回答