用过windows server做服务器的应该都遇到这种情况,通过远程桌面复制传输稍微大一点的文件经常会中断,简直令人抓狂。想过用FTP或SSH等来传文件,但是嫌安装配置麻烦,大材小用,就想着用简单的脚本来实现文件传输。
以下是服务器端ps1脚本:
$uploadDir = "D:\Server" #上传单文件到此目录,如服务器程序压缩包
$downloadDir = "D:\Redis\bak" #从此目录下载文件,如数据库或日志备份文件
$pwd = "E26AO42A" #简单设置密码,万一开启传输服务的时候被别人撞上了呢
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add("http://+:7808/") #监听7808端口
$listener.Start()
Write-Host "服务已启动"
while ($listener.IsListening) {
$context = $listener.GetContext()
$response = $context.Response
if ($context.Request.Headers["pwd"] -ne $pwd) {
$response.StatusCode = 403
$response.StatusDescription = "Forbidden"
} elseif ($context.Request.HttpMethod -eq "POST") {
$filename = $context.Request.Headers["filename"]
if($filename.Length -gt 0) {
$filepath = Join-Path $uploadDir $filename
$fs = New-Object System.IO.FileStream($filepath,2,2)
$context.Request.InputStream.CopyTo($fs)
$fs.Close()
Write-Host "接收文件成功:$filepath"
$response.StatusCode = 200
$response.StatusDescription = "OK"
} else {
$response.StatusCode = 400
$response.StatusDescription = "Bad Request"
}
} elseif ($context.Request.HttpMethod -eq "GET") {
$url = $context.Request.RawUrl
if($url -eq "/index") {
$files = Get-ChildItem -File -Path $downloadDir
$result = $files -Join "`n"
$buffer = [System.Text.Encoding]::Default.GetBytes($result)
$response.OutputStream.Write($buffer,0,$buffer.Length)
$response.StatusCode = 200
$response.StatusDescription = "OK"
} elseif (Test-Path -Path "$downloadDir$url" -PathType Leaf) {
$fs = New-Object System.IO.FileStream("$downloadDir$url",3,1)
$fs.CopyTo($response.OutputStream)
$response.StatusCode = 200
$response.StatusDescription = "OK"
} else {
$response.StatusCode = 404
$response.StatusDescription = "Not Found"
}
} else {
$response.StatusCode = 404
$response.StatusDescription = "Not Found"
}
$response.Close()
}
以下是客户端上传特定文件到服务器的ps1脚本:
$filePath = "ServerPack.rar" #要向服务器传输的单文件
$pwd = "E26AO42A" #密码与服务器端一致
Invoke-WebRequest -Uri "http://serverhost:7808" -Method POST -Headers @{"filename" = Split-Path $filePath -Leaf; "pwd" = $pwd} -InFile $filePath
pause
以下是客户端获取服务器的下载目录里的所有文件信息并可以下载指定文件的ps1脚本:
$url = "http://serverhost:7808/" #服务器地址
$downloadDir = "./" #下载下来的文件放在此目录
$pwd = "E26AO42A" #密码与服务器端一致
$response = Invoke-WebRequest -Uri ($url + "index") -Method GET -Headers @{"pwd" = $pwd}
$files = $response -Split "`n"
if ($files.Length -eq 0) {
Write-Host "没有可下载的文件"
pause
exit
}
$index = 0
$list = @()
foreach ($file in $files) {
$list += $file
Write-Host "$index $file"
$index += 1
}
while(1) {
$id = Read-Host "请输入要下载的文件序号"
if(($id -ge 0) -and ([int]$id -le $index)) {
Write-Host
Invoke-WebRequest -Uri ($url + $list[$id]) -Method GET -Headers @{"pwd" = $pwd} -OutFile ($downloadDir + $list[$id])
Write-Host "下载完成"
} else {
Write-Host "输入序号错误"
}
}