Post Tagged NetworkCredential

Powershell – Web (FTP) Request, Response

월요일, 07 7월 2010

Powershell 을 이용하여 웹 요청을 해보자. 웹 사이트를 관리 하거나 Rest 방식의 서비스를 사용 할 때 유용하다.

Get-WebResponseString

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Function Get-WebResponseString
{
    param (
        [Parameter(Mandatory=$true)]
        [String]$Url,      
        [Parameter(Mandatory=$true)]
        [String]$Method,
        [Parameter(Mandatory=$false)]
        [System.Net.NetworkCredential]$Credential
    )
   
    $Request = [System.Net.WebRequest]::Create($Url)   
    $Request.Method = $Method
   
    if ($Credential -ne $null)
    {
        $Request.Credentials = $credential
    }
   
    $Response = $Request.GetResponse()
   
    $StreamReader = New-Object System.IO.StreamReader $Response.GetResponseStream()
    $StreamReader.ReadToEnd()
}

사용 예

1
2
3
4
5
6
7
$Url = "http://Use-Powershell.com"
$Username = "talsu"
$Password = "pass1234"

$credential = New-Object System.Net.NetworkCredential @($Username, $Password)  

Get-WebResponseString -Url $Url -Credential $credential -Method "GET"

$Response 에서 결과 String을 반환 하지 않고 .StatusCode 등 다른 정보를 활용 할 수 있다.

Web 뿐만 아니라 FTP 에서도 동일하게 사용 할 수 있다.


Powershell – Web File Download , Upload

목요일, 07 7월 2010

Powershell을 이용하여 Linux의 wget과 같이 Web (http, ftp) 에서 File을 다운로드하고 업로드하는 스크립트를 만들어 보자.

.Net의 WebClient를 사용하면 간단하다.

Get-WebFile.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
param(
    [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
    [String[]]$FileURLs,
    [String]$SavePath = (Get-Location),
    [String]$Username,
    [String]$Password
)

if ( -not (Test-Path $SavePath))
{  
    return
}

foreach ($FileURL in $FileURLs)
{
    $Pieces = $FileURL.Split("/")
    $FileName = $Pieces[$Pieces.Count - 1]
    $FilePath = Join-Path $SavePath $FileName
   
    $Client = New-Object System.Net.WebClient
   
    if (($Username -ne $null) -and ($Password -ne $null))
    {      
        $Client.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)        
    }
   
    Write-Host ("[Download] {0} -> {1} ..." -f $FileURL, $FilePath) -NoNewline
    $Client.DownloadFile($FileURL, $FilePath)
    Write-Host " Finish"
}

핵심은 WebClient 개체를 만들고 DownloadFile 메서드를 호출 하는 것.

Upload도 마찬가지로 UploadFile 메서드를 호출 하면 된다.

Add-WebFile.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
param(
    [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
    [String[]]$Files,
    [Parameter(Mandatory=$true, Position=1)]
    [String]$TargetPath,
    [String]$Username,
    [String]$Password
)

foreach ($File in $Files)
{
    if (Test-Path $File)
    {
        $FileName = (Get-ChildItem $File).Name
        if ($TargetPath[$TargetPath.Length - 1] -ne "/") { $TargetPath += "/" }
       
        $TargetFullPath = ("{0}{1}" -f $TargetPath, $FileName)
        $Client = New-Object System.Net.WebClient
   
        if (($Username -ne $null) -and ($Password -ne $null))
        {      
            $Client.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
        }
        Write-Host ("[Upload] {0} -> {1} ..." -f $File, $TargetFullPath) -NoNewline
        $Client.UploadFile($TargetFullPath, $File)
        Write-Host " Finish"
    }
    else
    {
        Write-Host ("Wrong File Path : {0}" -f $File)
    }
}

이름 정하기가 까다롭다. Get-Verb 안에서 동사를 선택 하는데 Download, Upload 는 없으므로 Get , Add를 사용 했는데 적절 한지 모르겠다. Import, Export도 고려 해 봤지만 wget 명령이 생각 나서 Get은 쓰고 싶었고, 그렇다고 Upload를 Set으로 하는것도 마음에 안든다. Update 가 더 가까운 의미 인것 같기도 하다.