2014-07-15 6 views
1

scp 전송을 테스트하기위한 코드를 작성했습니다. 이것은 코드입니다. nexpect 모듈의 Node.js 대기 함수가 작동하지 않습니다.

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 [email protected]:~ success! 
from b.txt to [email protected]:~ success! 
from c.txt to [email protected]:~ success! 

을 예상하지만 출력은 내 기대와 달랐다. 내 node.js 모듈이 명령 행 입력을 대기 중입니다. 명령 줄 입력없이 코드를 어떻게 실행합니까?

답변

0

나는이 문제를 혼자서 해결했다.

node.js에서 scp를 사용하여 전송하려면 stdout 스트림에 대한 리디렉션이 필요합니다.

그래서 fs.readSync 기능을 사용하여/dev/stdout에 대한 리디렉션을 시도했습니다.

하지만 내 프로그램이 '알 수없는 오류'로 사망했습니다.

이 코드는 새로운 'scpFileTransfer'기능을 사용하여 'expect'프로그램을 사용하여 nexpect 모듈이나 리디렉션을 수행하지 않습니다.

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'프로그램이 설치되어 있는지 확인해야합니다.

그렇지 않은 경우 다음 명령을 사용하여 설치할 수 있습니다.


우분투 -는 sudo apt-get을

에 CentOS를 기대 설치 - (이미 운영 체제에 설치되어 있어야합니다.)


감사합니다 - 냠

맥 OS X를 기대하고 설치합니다.