作成 2015.10.29
更新 2015.10.29
PowerShell で FTPS アップロード
EnableSsl = true; を設定。FTPS であっても ftp:// で接続する。
FTPS サーバー単体では動作しますが、ロードバランサー経由では動きませんでした。
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$params = New-Object System.CodeDom.Compiler.CompilerParameters
$params.GenerateInMemory = $True
$params.TreatWarningsAsErrors = $True
$refs = "System.dll","mscorlib.dll"
$params.ReferencedAssemblies.AddRange($refs)

# C Sharp
$txtCode = '
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public class FTPSUploader {
  private string user_name = null;
  private string password = null;
  public FTPSUploader(){  }
  public void SetCredential(string sub_user, string sub_pass){
    user_name = sub_user;
    password = sub_pass;
  }
  public void Upload(String uri_path, String file_path){
    // 証明書を確認しない
    ServicePointManager.ServerCertificateValidationCallback = 
      new RemoteCertificateValidationCallback( 
        delegate(Object certsender, X509Certificate certificate,
        X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; });
    Uri uri = new Uri(uri_path);
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
    request.EnableSsl = true;
    request.KeepAlive = false;
    request.UseBinary = true;
    request.UsePassive = true;
    request.Credentials = new NetworkCredential(user_name, password); 
    request.Method = WebRequestMethods.Ftp.UploadFile;
      using (Stream stream = request.GetRequestStream())
      using (FileStream file_stream = new FileStream(file_path, FileMode.Open, FileAccess.Read)){
      Byte[] bytes = new Byte[8192];
      int read_size;
      while(true){
        read_size = file_stream.Read(bytes, 0, bytes.Length);
        if(read_size == 0){ break; }
        stream.Write(bytes, 0, read_size);
      }
    }
  }
}
'

$results = $provider.CompileAssemblyFromSource($params, $txtCode)
$results.Errors
$mAssembly = $results.CompiledAssembly
$i = $mAssembly.CreateInstance("FTPSUploader")
Try{
  if($results.Errors.Count -eq 0){
      $i.SetCredential("ユーザー名","パスワード")
      $i.Upload("ftp://ftpserver/upload/data1.txt", "C:\temp\data1.txt")
      $i.Upload("ftp://ftpserver/upload/data2.txt", "C:\temp\data2.txt")
      $i.Upload("ftp://ftpserver/upload/data3.txt", "C:\temp\data3.txt")
  }
}
Catch
{
  "アップロード失敗"
}

©2004-2017 UPKEN IPv4