Posted in: Powershell Automation

Upload files encrypted via SFTP using Powershell

This blogpost is about moving files over the internet in an old but secure way. I am going to write about automating the upload of files via STFP using Powershell and use encryption to do so. WinSCP is used to upload files and 7Zip (powershell module) is used for encrypting the files. We are going to use task scheduler to create a task which uploads a file each day.

Preparation uploading files encrypted via SFTP using Powershell

We need to install 2 applications. WinSCP is available as application, this is a download link. Furthermore we need to install the 7Zip powershell module. You can do so by using the following command:

Install-Module -Name 7Zip4Powershell

Now we need to create 2 config files to store the encypted passwords. Firstly, you need to start with running Powershell as the user that you are going to schedule the task with. Otherwise you the user which runs the task can’t decrypt the passwords we are going to use in the config files.

Hold shift and right mouse click a Powershell icon you will get the option to run as a different user:

Run Powershell as different user

We are now encrypting the encryptionkey used to encrypt the archive we are going to build with 7Zip.

You can do so by using the following code: (you need to enter the encryption key you want to use to encrypt the 7Zip archive)

$securePassword = Read-host -AsSecureString | ConvertFrom-SecureString

$securePassword | Out-File -FilePath C:\MyPasswords\password.txt #Use Accordingly

Enter the path of this in the value of the script called $EncryptedPassword

Next up is the config file for WinSCP. (We still use the Powershell session started by the user which runs the scheduled task).

Run the following code again: (you need to enter the password of the SFTP useraccount)

$securePassword = Read-host -AsSecureString | ConvertFrom-SecureString

$securePassword | Out-File -FilePath C:\MyPasswords\WinSCPConfig.xml #Use Accordingly

We need edit this file. Edit this file so that it has the following content: (Change the SFTPUSERNAME accordingly)

Encrypted password

Last but not least we need to create the scheduled task.

Go to the task scheduler and create a task:

Upload files encrypted via SFTP using Powershell

Enter a name and select the user which you used to create the encrypted passwords:

Create a schedule:

Upload files encrypted via SFTP

Create a new action and select powershell to run. In addition, you need enter to following at “add arguments”: -ExecutionPolicy ByPass -File “C:\PathtoFile.ps1”

Powershell task

The task is created. You need to fill in the variables in the script. Please keep in mind that you need to fill in the variables.

Upload Script

Fill in all the variables:

$EncryptedPassword = Get-Content -Path "Path to password.txt" | ConvertTo-SecureString
$decPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Encryptedpassword))
$SshHostKeyFingerprint="Enter SSH Keyprint"
$sftp_host="Enter IP Address"
$sftp_folder="FolderName"
$SourceFolder="FolderName"
$WinSCPConfigFile="Path to Config.xml"
$7ZipSourceFilePath="FilePath to Source"
$7ZipArchiveFilePath="FilePath to Archive"
$WinSCPDLL="C:\Program Files (x86)\WinSCP\WinSCPnet.dll" #Use Accordingly

#bestanden versleutelen
Compress-7Zip -Path $7ZipSourceFilePath -ArchiveFileName $7ZipArchiveFilePath -Format SevenZip -Password $decPassword -EncryptFilenames

# Read XML configuration file
[xml]$config = Get-Content $WinSCPConfigFile
try
{
    # Load WinSCP .NET assembly
    Add-Type -Path $WinSCPDLL
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = $sftp_host
        UserName = $config.Configuration.UserName
        SecurePassword = ConvertTo-SecureString $config.Configuration.Password
        SshHostKeyFingerprint = $SshHostKeyFingerprint
    }
    $session = New-Object WinSCP.Session
    try
    {
        # Connect
        $session.Open($sessionOptions)
        # Upload files
        $transferOptions = New-Object WinSCP.TransferOptions
        $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
        $transferResult =
            $session.PutFiles($SourceFolder, $sftp_folder, $False, $transferOptions)
        # Throw on any error
        $transferResult.Check()
        # Print results
        foreach ($transfer in $transferResult.Transfers)
        {
            Write-Host "Upload of $($transfer.FileName) succeeded"
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
}

References

Creating Encrypted Password

Upload Files using WinSCP & Powershell

Automate Exchange Online connection with Powershell

Leave a Reply