본문 바로가기
컴퓨터/Node.js

Node.js 에서 client 로 부터 command 받아 shell 에서 실행하기

by HanJoohyun 2017. 7. 2.
반응형



안녕하세요 한주현입니다



오늘 포스팅은 nodejs 로 구성한 서버에서

client 로 부터 command 를 받아 shell 에서 그 command 를 실행하는 방법에 대해 포스팅 하겠습니다.




준비물

1. 맥 or 리눅스

2. node js

3. express js



# node js 설치

다음 페이지에 접속하셔서 node js 를 다운받아 설치합니다.

https://nodejs.org/en/


저는 v6.11.0 를 사용하고 있습니다


제대로 설치하셨다면 다음 command 를 실행이 가능하실겁니다


$ node -v

v6.11.0



# express 설치

다음 페이지를 참조하셔서 express js 를 설치해봅시다


http://expressjs.com/en/starter/installing.html

http://expressjs.com/en/starter/generator.html




# express generator 로 웹서비스 시작하기

express 를 설치하셨다면 express generator 로 웹서비스를 시작해봅시다

http://expressjs.com/en/starter/generator.html


express 의 실행 도움말은 다음과 같습니다

$ express -h


  Usage: express [options] [dir]


  Options:


    -h, --help           output usage information

        --version        output the version number

    -e, --ejs            add ejs engine support

        --pug            add pug engine support

        --hbs            add handlebars engine support

    -H, --hogan          add hogan.js engine support

    -v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)

    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)

        --git            add .gitignore

    -f, --force          force on non-empty directory


저는 pug (구 jade) 의 축약된 문법이 기발하다고는 생각하나,

여러 사람과 개발 할 때는 그래도 html 의 형태를 보존하고 있는 ejs 가 더 낫다 생각하여 이번 실습은 ejs 로 가보겠습니다


$ express -v ejs test_server

$ cd test_server && npm install

$ DEBUG=test-server:* npm start


이렇게 하시면 포트 3000번으로 웹서비스를 시작하실 수 있습니다 ㅎㅎ


만약 3000 말고 다른 포트를 사용하시고 싶으시면,


./bin/www 파일에서 3000 을 다른 번호로 바꾸시면 됩니다


var port = normalizePort(process.env.PORT || '3000');


저는 3002 로 하였습니다




# 새로운 page 생성

이 단계까지 오셨으면 기본적으로 index와  users 페이지가 생성되었습니다


localhost:<포트번호> 로 접속하면 아래와 같이 나오게 됩니다



우리는 cmd 라는 페이지를 만들어서

text input 을 받아 그 결과를 browser에 출력하는 페이지를 만들겠습니다


아래의 파일들을 차근차근 수정해보도록 하겠습니다

빨간 bold 부분이 추가된 부분입니다


/app.js

var express = require('express');

...

var index = require('./routes/index');

var users = require('./routes/users');

var cmd = require('./routes/cmd');


...


app.use('/', index);

app.use('/users', users);

app.use('cmd', cmd);


/routes/cmd.js

var express = require('express');                                

var router = express.Router();

var exec = require("child_process").exec;


router.get('/', function(req, res, next) {

    console.log(req.query.cmd);

    exec(req.query.cmd, function (err, stdout, stderr) {


    //Print stdout/stderr to console

    console.log(stdout);

    console.log(stderr);


    //Simple response to user whenever localhost:3003 is accessed

    res.render('cmd', { title: 'Express', data: stdout });

  });

});


module.exports = router;


/views/cmd.ejs

<!DOCTYPE html>                                            

<html>

  <head>

    <title><%= title %></title>

    <link rel='stylesheet' href='/stylesheets/style.css' />

  </head>

  <body>

    <h1>cmd <%= title %></h1>

    <p>Welcome to <%= data %></p>

    <form id='target'action='cmd'>

      <input id='target_input' name='cmd' type='text'>

      <input type='submit' value='submit'>

    </form>

    <h1><%= data %></h1>

  </body>

</html>





실행


localhost:<포트번호>/cmd 에 접속하시면 아래와 같이 나오게 됩니다.



input 에 명령어를 쓰시고 submit 을 하게 되면

아래와 같은 결과를 얻게 됩니다 ㅎㅎ




이를 응용하면 여타 서버 스크립트를 실행 할 수 있겠지요?




node js 로 즐거운 개발하시기를 바라며

그럼 다음 시간에 만나요~




반응형

댓글