node.js 로 linux shell script 실행하기
Ubuntu Linux 에 node.js 를 설치하고, 환경을 만듭니다.
https://full-stack-developer.tistory.com/3?category=888454
Express 설치 설정
Express 는 Node.js 위에서 돌아가는 Framework로 쉽게 node.js based web server 를 만들수 있도록 많은 기능들을 제공한다. 전세계 적으로 많은 회사 들에서 Express 를 사용하고 있다. command prompt 를 열고..
full-stack-developer.tistory.com
project_root /app.js 를 생성하고 아래와 같이 코딩합니다.
const express = require('express')
const app = express() //express object
const path = require('path')
const ejs = require('ejs') //ejs object
const bodyParser = require('body-parser')
app.set('port',process.env.PORT || 8001)
app.set('view engine','ejs')
app.set('views', './views');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
var exec = require('child_process').exec
var child
//Post
app.post('/shell',(req,res)=>{
console.log(req.body)
res.redirect('/')
})
//Get
app.get('/',async(req,res)=>{
child = exec('./util/test.sh',
function (err, stdout, stderr) {
console.log('stdout: '+stdout)
console.log('stderr: '+stderr)
if(err !== null)
{
console.log('exec error: '+err)
}
res.render('shell', {
nout : stdout,
eout : stderr
})
})
})
app.listen(app.get('port'),()=>{
console.log('express server listening on port ' + app.get('port'))
})
project_root /util/test.sh 를 생성하고, 아래와 같이 코딩 합니다. (이것은 linux bash shell 에서 구동되는 shell script 로써 , nvme-cli 라는 프로그램을 사용하여, SSD 를 컨트롤 하는 구문 입니다. 실습시 echo "hello world" 와 같은 간단한 문장만 넣고 진행해도 무방합니다.)
#!/bin/bash
echo ""
echo ""
echo ""
echo "nvme list"
nvme list
echo ""
echo ""
echo ""
echo "nvme id-ctrl /dev/nvme0"
nvme id-ctrl /dev/nvme0
project_root /views/shell.ejs 를 생성하고, 아래와 같이 코딩 합니다.
<!DOCTYPE html>
<html lang="ko">
<body>
Test Result : <br/> <%=nout%> <br/><br/>
Test Error : <br/> <%=eout%> <br/><br/>
</body>
</html>
<실습 방법은 아래와 같습니다>
Ubuntu Server 의 IP address 가 10.16.10.125 라고 가정하고,
Ubuntu Server 에서 "node app.js" 하여 web server를 실행합니다.
다른 client PC 에서 Web brower 를 열고, "http://10.16.10.125:8001/" 라고 입력하면,
shell이 실행되고, 그 return 값이 web 상에 display 됩니다.