본문 바로가기
블로그 이미지

방문해 주셔서 감사합니다! 항상 행복하세요!

  
   - 문의사항은 메일 또는 댓글로 언제든 연락주세요.
   - "해줘","답 내놔" 같은 질문은 답변드리지 않습니다.
   - 메일주소 : lts06069@naver.com


Node.js

Node.js node-ssh 클라이언트

야근없는 행복한 삶을 위해 ~
by 마샤와 곰 2019. 4. 27.

 

 

윈도우서버, 리눅스서버에서 ssh를 활용하여 접속해서 명령을 수행 해야 되는 경우가 생겼다.
자바나 php로 된 대부분의 라이브러리들이..이상하게도 윈도우 서버만 만나면 timeout이 걸리거나 커넥션이 리셋되면서 명령어를 끝까지 수행하지 못하는 현상이 계속 발생 하였다.
물론 대부분의 서버가 리눅스이긴 하지만, 이번처럼 윈도우 서버에서 해야되는 특이한 경우를 대비해서..이것저것 해 보다가 node.js로 된 괜찮은 모듈을 발견 하였다.
먼저 node-ssh 라는 모듈을 설치한다.

npm install node-ssh

    var node_ssh = require('node-ssh');
    var ssh = new node_ssh();
    var conn = ssh.connect({
        host: 주소,
        username: 아이디,
        port: 포트번호,
        password : 비번,
        readyTimeout : 타임아웃시간..
    });

//명령어 보내기   
ssh.execCommand('원하는 명령어', { }).then(function(result) {
	console.log('결과: ' + result.stdout);
	console.log('에러: ' + result.stderr);
    ssh.dispose();//커넥션 종료
});

//파일 받기
ssh.getFile('로컬 경로', '서버에서 받을 파일').then(function(Contents) {
	console.log("DONE");
  }, function(error) {
	console.log(error);
}).then(function(){
	ssh.dispose(); //커넥션 종료
});

//파일 보내기
ssh.putFiles([{ local: '보낼파일', remote: '저장할 주소' }]).then(function() {
	console.log("DONE");
  }, function(error) {
	console.log(error);
  }).then(function(){
	ssh.dispose();  //커넥션 종료
});

위 예제처럼 한다면 커넥션 끊을 때 에러(?)메시지가 등장하지만 이상없이 명령을 수행 한다.
해당 소스코드 그대로 복붙하면 명령 한번날리고 종료되겠지만, 
명령을 이어서 계속 하려면 then을 활용하여 원하는 명령을 계속 수행 할 수 있다.

//then 지옥...
ssh.execCommand('원하는 명령어1', { }).then(function(result) {
	console.log('결과: ' + result.stdout);
	console.log('에러: ' + result.stderr);
   ssh.execCommand('원하는 명령어2', { }).then(function(result) {
	   console.log('결과: ' + result.stdout);
	   console.log('에러: ' + result.stderr);
       ssh.execCommand('원하는 명령어3', { }).then(function(result) {
	       console.log('결과: ' + result.stdout);
	       console.log('에러: ' + result.stderr);
       });
   });
})

해당 메소드가 Promise 객체를 리턴하기 때문에 then으로 이어가야 한다.

then으로 안하면 이벤트 루프 때문에 다소 당황스러운 결과를 보게 될 것이다..

반응형
* 위 에니메이션은 Html의 캔버스(canvas)기반으로 동작하는 기능 입니다. Html 캔버스 튜토리얼 도 한번 살펴보세요~ :)
* 직접 만든 Html 캔버스 애니메이션 도 한번 살펴보세요~ :)

댓글