Enterprise IT Solutions/Microsoft

[PowerShell] HTTP 서버 만들기

iseop 2019. 10. 21. 22:03   인쇄용 버전

1. 개요

System.Net.HttpListener는 .NET Framework 2.0에서 도입된 클래스인데, 파워셸과 닷넷만 설치되어 있으면(대부분 Windows 7 이상에서) 사용할 수 있습니다. 이 클래스를 이용해서 현재 디렉터리에 있는 파일을 Plaintext로 보여주는 간단한 웹 서버를 만들 수 있습니다. 

2. 예제

$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add("http://localhost:8080/")
$directoryroot = (pwd).Path

try {
    $listener.Start()
} catch {
    "Unable to start listener."
    exit 1
}

while ($listener.IsListening) {
    $context = $listener.GetContext()
    $requestUrl = $null
    $content = $null
    $requestUrl = $directoryroot + '\' + $context.Request.Url.LocalPath
    $response = $context.Response
    $response.ContentType = "text/html"
    $rawcontent = Get-Content $requestUrl
    $content = [System.Text.Encoding]::UTF8.GetBytes($rawcontent)
    $response.OutputStream.Write($content, 0, $content.Length)
    $response.Close()
}

예외 처리 등은 포함하지 않고 요청한 파일이 존재할 경우에만 내용을 보여줍니다.

2. 1. 실행 결과

PS C:\Users\test> wget http://localhost:8080/index.html


StatusCode        : 200
StatusDescription : OK
Content           : test
RawContent        : HTTP/1.1 200 OK
                    Transfer-Encoding: chunked
                    Content-Type: text/html
                    Date: Mon, 21 Oct 2019 13:01:46 GMT
                    Server: Microsoft-HTTPAPI/2.0

                    test
Forms             : {}
Headers           : {[Transfer-Encoding, chunked], [Content-Type, text/html], [Date, Mon, 21 Oct 2019 1
                    3:01:46 GMT], [Server, Microsoft-HTTPAPI/2.0]}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 4