This is an old revision of the document!

Documentation » Using WinSCP » Guides » Scripting/Automation »

Protecting credentials used for automation

When writing a script file or a code using .NET assembly, you need to store credentials (such as a username and a password) somewhere. Storing them in the script/code directly has obvious disadvantages, for example:

  • The script/code is often stored in a revision control system, making the credentials easily accessible.
  • The script/code may often need to be accessible on the production system for review or auditing purposes or reuse, while the credentials should not.

Advertisement

Solution is to separate the credentials from the script/code into a configuration file. While the script/code without explicit credentials can be safely stored into a revision system and be otherwise accessible, the configuration file should be protected as much as possible. Particularly its file permissions should be restricted only to administrators (for writing) and user under which the script/code runs (for reading). The configuration file can also be encrypted, for example with built-in NTFS filesystem-level encryption.

Using WinSCP scripting

In script, you can replace actual credentials with reference to environment variables. You can then call WinSCP from a batch file that sets these variables. The batch file itself then serves as a “configuration file”.

For example, following script (example.txt):

option batch abort
option confirm off
open sftp://%USERNAME%:%PASSWORD%@example.com
...

can be called from this batch file (“configuration file”):

@echo off
set USERNAME=martin
set PASSWORD=mypassword
winscp.com /script=example.txt

Advertisement

Using WinSCP .NET assembly

PowerShell

In PowerShell code using WinSCP .NET library you can use Get-Content cmdlet to read an XML configuration file.

For example with following XML configuration file (config.xml):

<Configuration>
  <UserName>martin</UserName>
  <Password>mypassword</Password>
</Configuration>

use this PowerShell code to read and use it:

# Read XML configuration file
[xml]$config = Get-Content ".\config.xml"
 
# Use read credentials
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "example.com"
$sessionOptions.UserName = $config.Configuration.UserName
$sessionOptions.Password = $config.Configuration.Password
 
...

SSIS

In SSIS, you can configure script variables in SSIS > Variables. To make them accessible from the script task, in the context menu of the task, choose Edit. On the Script task editor on Script page, select ReadOnlyVariables, and tick the below properties.

See SSIS example.

Last modified: by 213.125.68.178