かなり前に書いた「bat(バッチ):WindowsバッチでFTPを自動化実行する」のブログに
未だにアクセスがあり、今時FTPはないだろうなと思ったので、
SFTPでできるか調査、作成してみましたので、参考にしてみてください。
基本的にFTPバッチと同じような作りになるようにしています。
大したテストや実運用はしていないので、不具合があった際はご容赦ください。
実行にあたって、以下の前提条件があります。
・標準のSFTPコマンドだけでは無理だったので「WinSCP」を使用
(インストールされるフォルダの「Program Files (x86)」は空白ブランクがあるので、使用時はダブルクォーテーションで囲む)
・パスワードではなくキー認証によるログイン
(事前に、ユーザーフォルダの.sshにキーファイルを保存
・キーファイルは、WinSCPのツールを使ってPEMからPPKに変更
【sftp_sample.ps1】
# カレントディレクトリ取得
$current = (Convert-Path .)
# SFTP用コマンド作成ファイル
$sftpcommand = $current + "\sftpcommand.txt"
# 年月セット
$dirym = Get-Date -Format "yyyyMM"
# 年月日セット
$dirymd = Get-Date -Format "yyyyMMdd"
# ログファイル保存用ディレクトリ作成
if ( !(Test-Path .\LOG) ) {
mkdir ./LOG
}
# ログファイル
$logfile = $current + "\LOG\ftplog_" + $dirymd + ".log"
# ログファイル出力用日時情報
$now = Get-Date -Format "yyyy/MM/dd HH:mm:ss"
# スクリプトファイル名
$name = $myInvocation.MyCommand.name
# ログファイル出力
$outline = $now + " : [" + $name + "] Started!!"
Write-Output $outline | Out-File -FilePath $logfile
# 取得ファイル保存用ディレクトリ作成
if ( !(Test-Path .\$dirym) ) {
mkdir ./$dirym
}
# 取得ファイル保存用ディレクトリ移動
cd ./$dirym
Write-Host (Convert-Path .)
# SFTPコマンド作成 ==================================================================
Write-Output "option batch abort" | Out-File -FilePath $sftpcommand
Write-Output "option confirm" | Add-Content $sftpcommand
# ログインコード:黄色の個所は各環境に合わせて変更
Write-Output "open sftp://ec2-user@ec2-**-***-***-***.ap-northeast-1.compute.amazonaws.com -privatekey=C:\USERS\login-user\.ssh\key_pair.ppk" | Add-Content $sftpcommand
# 以下はログインしたサーバーサイドで必要な処理に合わせて変更
Write-Output "cd " | Add-Content $sftpcommand
Write-Output "cd test" | Add-Content $sftpcommand
Write-Output "mget *.csv" | Add-Content $sftpcommand
Write-Output "exit" | Add-Content $sftpcommand
# SFTPコマンド END ==================================================================
# SFTP実行
C:\"Program Files (x86)"\WinSCP\WinSCP.com /script=$sftpcommand | Add-Content $logfile
# ログファイル出力
$now = Get-Date -Format "yyyy/MM/dd HH:mm:ss"
$outline = $now + " : [" + $name + "] Ended!!"
Write-Output $outline | Add-Content $logfile
Write-Host "Finished"
pause
PowerShellの参考