javascript로 ssh 접속하기

세니·2024년 3월 18일
0
post-thumbnail

보통 프로젝트를 배포할때 리눅스 환경에서 수행되는 경우가 있는데 이때 ssh로 접속하는 경우가 많다!

javascript를 사용하는 나에게 ssh를 직접 접속해서 하는 방법만 있는줄 알았는데 npm package로 ssh를 접속할 수 있었다.

여러가지(ssh2, tunnel-ssh, node-ssh..)가 있는데 그 중 사용하기 쉬운 node-ssh에 대해 몇 글자 적어보겠다.

node-ssh

node-ssh npm 설명

주요 함수로는 connect, putFile, putFiles, getFile, putDirectory, execCommand, exec 등이 있다.

  1. connect는 ssh 접속하는 기능
  2. putFile은 파일을 업로드
  3. putFiles는 파일 여러개를 업로드
  4. getFile는 파일 다운로드
  5. putDirectory는 폴더 업로드
  6. execCommand 명령어 입력 후 실행
  7. exec는 명령어 입력 후 실행

일단 execCommand와 exec의 차이점은 execCommand는 명령어 입력 후 리턴값으로 결과, 에러를 반환하는데 exec는 오로지 결과만 반환한다.

사용법 예시

const fs = require('fs')
const path = require('path')
const {NodeSSH} = require('node-ssh')

const ssh = new NodeSSH()

ssh.connect({
  host: '111.111.11.11',
  port: '3003',
  username: 'steel',
  password: 'password'
}).then((res) => {
  // .. 완료 동작 정의
});

// 옮길 파일과 옮길 파일이 위치할 경로를 적는다.
ssh.putFile('local file path','remote file path').then((res) => {});

// 옮길 파일과 파일이 위치할 경로를 {}로 감싸 배열로 보낸다.
ssh.putFiles([{'file1','path1'}, {'file2','path2'}]).then((res) => {});

// 다운받고 저장될 위치와 다운하는 경로를 적는다.
ssh.getFile('localpath1','remotepath1').then((res) => {});

/* 
  실행할 명령어를 적고, cwd는 명령어를 수행할 경로를 적어야 한다.
  이때 유의할 점은 절대 경로를 적어야 잘 인식한다.
  물론 cd 명령어를 이용해서 할 수 있지만 cwd로 정의하면 명령어를 줄일 수 있다.
*/
ssh.execCommand('rm -rf target',{ cwd: '/var/www' }).then((res) => {});

위와 같이 사용 방법은 매우 간단하다!

이 외에도 많지만 유용하다고 생각되는점은 사용하는 함수는 Promise를 반환하기에 async await로 변경이 가능하다.


node-ssh 링크를 보게 되면 API가 많기 때문에 참고하면 되겠다.

profile
세니는 무엇을 하고 있을까

0개의 댓글