PowerShell을 사용하여 FTP로 파일 업로드
PowerShell을 사용하여 FTP를 사용하여 익명 FTP 서버로 파일을 전송하고 싶습니다.추가 패키지는 사용하지 않을 겁니다. 어떻게요?
스크립트가 정지하거나 크래시하지 않도록 100% 방탄할 수 있을지는 잘 모르겠습니다.업로드 중에 서버의 전원이 끊기면 어떻게 됩니까?이것에 의해, 다음의 조작을 개시할 수 있는 견고한 기반이 됩니다.
# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes("C:\me.png")
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()
다른 방법도 있어요.다음 스크립트를 사용하고 있습니다.
$File = "D:\Dev\somefilename.zip";
$ftp = "ftp://username:password@example.com/pub/incoming/somefilename.zip";
Write-Host -Object "ftp url: $ftp";
$webclient = New-Object -TypeName System.Net.WebClient;
$uri = New-Object -TypeName System.Uri -ArgumentList $ftp;
Write-Host -Object "Uploading $File...";
$webclient.UploadFile($uri, $File);
또한 다음 명령을 사용하여 Windows FTP 명령줄 유틸리티에 대해 스크립트를 실행할 수 있습니다.
ftp -s:script.txt
SO에 대한 다음 질문도 이에 대한 답변입니다.FTP 업로드 및 다운로드 스크립팅 방법
이게 가장 높은 투표율을 기록한 해결책보다 더 우아하다고 주장하진 않을 거야근데 이게 멋있어(최소한 내 마음속에서는 LOL)
$server = "ftp.lolcats.com"
$filelist = "file1.txt file2.txt"
"open $server
user $user $password
binary
cd $dir
" +
($filelist.split(' ') | %{ "put ""$_""`n" }) | ftp -i -in
보시는 바와 같이 dinky 빌트인 Windows FTP 클라이언트를 사용합니다.훨씬 짧고 직설적이기도 합니다.네, 실제로 써봤는데 효과가 있어요!
가장 쉬운 방법
PowerShell을 사용하여 FTP 서버에 바이너리 파일을 업로드하는 가장 간단한 방법은 다음을 사용하는 것입니다.
$client = New-Object System.Net.WebClient
$client.Credentials =
New-Object System.Net.NetworkCredential("username", "password")
$client.UploadFile(
"ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")
고급 옵션
더 나은 제어가 필요하다면WebClient는 (TLS/SSL 암호화 등)를 제공하지 않습니다.를 사용합니다.간단한 방법은 복사만 하면 됩니다.FileStream를 사용하여 FTP 스트림에 접속합니다.
$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials =
New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()
$fileStream.CopyTo($ftpStream)
$ftpStream.Dispose()
$fileStream.Dispose()
진행 상황 모니터링
업로드 진행 상황을 모니터링해야 하는 경우 콘텐츠를 청크로 직접 복사해야 합니다.
$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials =
New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()
$buffer = New-Object Byte[] 10240
while (($read = $fileStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
$ftpStream.Write($buffer, 0, $read)
$pct = ($fileStream.Position / $fileStream.Length)
Write-Progress `
-Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) `
-PercentComplete ($pct * 100)
}
$ftpStream.Dispose()
$fileStream.Dispose()
폴더 업로드 중
폴더의 모든 파일을 업로드 하는 경우는, 을 참조해 주세요.
전체 폴더를 FTP에 업로드하는 PowerShell 스크립트
최근 FTP와 통신하기 위한 몇 가지 함수를 powershell에 썼습니다.https://github.com/AstralisSomnium/PowerShell-No-Library-Just-Functions/blob/master/FTPModule.ps1 를 참조하십시오.다음 두 번째 기능에서는 로컬 폴더 전체를 FTP로 전송할 수 있습니다.이 모듈에는 폴더와 파일을 재귀적으로 삭제/추가/읽기 위한 기능도 있습니다.
#Add-FtpFile -ftpFilePath "ftp://myHost.com/folder/somewhere/uploaded.txt" -localFile "C:\temp\file.txt" -userName "User" -password "pw"
function Add-FtpFile($ftpFilePath, $localFile, $username, $password) {
$ftprequest = New-FtpRequest -sourceUri $ftpFilePath -method ([System.Net.WebRequestMethods+Ftp]::UploadFile) -username $username -password $password
Write-Host "$($ftpRequest.Method) for '$($ftpRequest.RequestUri)' complete'"
$content = $content = [System.IO.File]::ReadAllBytes($localFile)
$ftprequest.ContentLength = $content.Length
$requestStream = $ftprequest.GetRequestStream()
$requestStream.Write($content, 0, $content.Length)
$requestStream.Close()
$requestStream.Dispose()
}
#Add-FtpFolderWithFiles -sourceFolder "C:\temp\" -destinationFolder "ftp://myHost.com/folder/somewhere/" -userName "User" -password "pw"
function Add-FtpFolderWithFiles($sourceFolder, $destinationFolder, $userName, $password) {
Add-FtpDirectory $destinationFolder $userName $password
$files = Get-ChildItem $sourceFolder -File
foreach($file in $files) {
$uploadUrl ="$destinationFolder/$($file.Name)"
Add-FtpFile -ftpFilePath $uploadUrl -localFile $file.FullName -username $userName -password $password
}
}
#Add-FtpFolderWithFilesRecursive -sourceFolder "C:\temp\" -destinationFolder "ftp://myHost.com/folder/" -userName "User" -password "pw"
function Add-FtpFolderWithFilesRecursive($sourceFolder, $destinationFolder, $userName, $password) {
Add-FtpFolderWithFiles -sourceFolder $sourceFolder -destinationFolder $destinationFolder -userName $userName -password $password
$subDirectories = Get-ChildItem $sourceFolder -Directory
$fromUri = new-object System.Uri($sourceFolder)
foreach($subDirectory in $subDirectories) {
$toUri = new-object System.Uri($subDirectory.FullName)
$relativeUrl = $fromUri.MakeRelativeUri($toUri)
$relativePath = [System.Uri]::UnescapeDataString($relativeUrl.ToString())
$lastFolder = $relativePath.Substring($relativePath.LastIndexOf("/")+1)
Add-FtpFolderWithFilesRecursive -sourceFolder $subDirectory.FullName -destinationFolder "$destinationFolder/$lastFolder" -userName $userName -password $password
}
}
여기 제 슈퍼 쿨 버전이 있습니다.프로그레스 바가 있기 때문입니다:-)
전혀 쓸모없는 기능인 것은 알지만, 그래도 멋있어 보입니다.\ m / \ m /
$webclient = New-Object System.Net.WebClient
Register-ObjectEvent -InputObject $webclient -EventName "UploadProgressChanged" -Action { Write-Progress -Activity "Upload progress..." -Status "Uploading" -PercentComplete $EventArgs.ProgressPercentage } > $null
$File = "filename.zip"
$ftp = "ftp://user:password@server/filename.zip"
$uri = New-Object System.Uri($ftp)
try{
$webclient.UploadFileAsync($uri, $File)
}
catch [Net.WebException]
{
Write-Host $_.Exception.ToString() -foregroundcolor red
}
while ($webclient.IsBusy) { continue }
PS. '동작 정지했나, 아니면 ASDL 접속이 느린가?'라고 생각할 때 많은 도움이 됩니다.
이와 같이 PowerShell을 통해 파일 업로드를 간단히 처리할 수 있습니다.프로젝트 전체는 Github에서 구할 수 있습니다.https://github.com/edouardkombo/PowerShellFtp
#Directory where to find pictures to upload
$Dir= 'c:\fff\medias\'
#Directory where to save uploaded pictures
$saveDir = 'c:\fff\save\'
#ftp server params
$ftp = 'ftp://10.0.1.11:21/'
$user = 'user'
$pass = 'pass'
#Connect to ftp webclient
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
#Initialize var for infinite loop
$i=0
#Infinite loop
while($i -eq 0){
#Pause 1 seconde before continue
Start-Sleep -sec 1
#Search for pictures in directory
foreach($item in (dir $Dir "*.jpg"))
{
#Set default network status to 1
$onNetwork = "1"
#Get picture creation dateTime...
$pictureDateTime = (Get-ChildItem $item.fullName).CreationTime
#Convert dateTime to timeStamp
$pictureTimeStamp = (Get-Date $pictureDateTime).ToFileTime()
#Get actual timeStamp
$timeStamp = (Get-Date).ToFileTime()
#Get picture lifeTime
$pictureLifeTime = $timeStamp - $pictureTimeStamp
#We only treat pictures that are fully written on the disk
#So, we put a 2 second delay to ensure even big pictures have been fully wirtten in the disk
if($pictureLifeTime -gt "2") {
#If upload fails, we set network status at 0
try{
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
} catch [Exception] {
$onNetwork = "0"
write-host $_.Exception.Message;
}
#If upload succeeded, we do further actions
if($onNetwork -eq "1"){
"Copying $item..."
Copy-Item -path $item.fullName -destination $saveDir$item
"Deleting $item..."
Remove-Item $item.fullName
}
}
}
}
다음 기능을 사용할 수 있습니다.
function SendByFTP {
param (
$userFTP = "anonymous",
$passFTP = "anonymous",
[Parameter(Mandatory=$True)]$serverFTP,
[Parameter(Mandatory=$True)]$localFile,
[Parameter(Mandatory=$True)]$remotePath
)
if(Test-Path $localFile){
$remoteFile = $localFile.Split("\")[-1]
$remotePath = Join-Path -Path $remotePath -ChildPath $remoteFile
$ftpAddr = "ftp://${userFTP}:${passFTP}@${serverFTP}/$remotePath"
$browser = New-Object System.Net.WebClient
$url = New-Object System.Uri($ftpAddr)
$browser.UploadFile($url, $localFile)
}
else{
Return "Unable to find $localFile"
}
}
이 함수는 지정된 파일을 FTP로 전송합니다.다음 파라미터를 사용하여 함수를 호출해야 합니다.
- userFTP = 기본적으로 "삭제"되거나 사용자 이름
- 기본적으로 passFTP = "비밀번호" 또는 암호
- serverFTP = FTP 서버의 IP 주소
- localFile = 전송할 파일
- remotePath = FTP 서버의 경로
예를 들어 다음과 같습니다.
SendByFTP -userFTP "USERNAME" -passFTP "PASSWORD" -serverFTP "MYSERVER" -localFile "toto.zip" -remotePath "path/on/the/FTP/"
Goyuix의 솔루션은 정상적으로 동작하지만 제시된 바와 같이 "요청된 FTP 명령어는 HTTP 프록시를 사용할 때 지원되지 않습니다."라는 오류가 나타납니다.
행 뒤에 이 합니다.$ftp.UsePassive = $true이치노
$ftp.Proxy = $null;
컬을 설치할 수 있다면 간단한 솔루션.
curl.exe -p --insecure "ftp://<ftp_server>" --user "user:password" -T "local_file_full_path"
언급URL : https://stackoverflow.com/questions/1867385/upload-files-with-ftp-using-powershell
'programing' 카테고리의 다른 글
| Azure VM 임시 스토리지는 얼마나 일시적입니까? (0) | 2023.04.21 |
|---|---|
| VBA에서 "종료"와 "종료 서브"의 차이점은 무엇입니까? (0) | 2023.04.21 |
| 특정 컬럼 openpyxl의 모든 행을 반복하다 (0) | 2023.04.21 |
| RSA 개인 키에 대한 Opensh 개인 키 (0) | 2023.04.21 |
| WPF 버튼을 ViewModelBase 명령어에 바인드하려면 어떻게 해야 합니까? (0) | 2023.04.21 |