### Basic Inno Setup Script for WinSCP
Source: https://winscp.net/eng/docs/custom_distribution
A fundamental Inno Setup script for creating a custom WinSCP installer. It includes sections for application details, file installation, shortcuts, registry settings, and post-installation actions.
```inno setup
[Setup]
AppName=WinSCP (provided by Some Company)
AppVerName=WinSCP 5.0
DefaultDirName={pf}\WinSCP
DefaultGroupName=WinSCP (provided by Some Company)
AppMutex=WinSCP
[Files]
Source: "WinSCP.exe"; DestDir: "{app}"; \
Flags: ignoreversion
Source: "DragExt.dll"; DestDir: "{app}"; \
Flags: regserver restartreplace uninsrestartdelete
[Icons]
Name: "{group}\WinSCP"; Filename: "{app}\WinSCP.exe"
Name: "{userdesktop}\WinSCP"; Filename: "{app}\WinSCP.exe"
[Registry]
#define RegistryKey "Software\Martin Prikryl\WinSCP 2"
Root: HKCU; SubKey: "{#RegistryKey}\Configuration\Interface"; ValueType: dword; \
ValueName: "Interface"; ValueData: 1
Root: HKCU; SubKey: "{#RegistryKey}\Configuration\Interface"; ValueType: dword; \
ValueName: "DDExtEnabled"; ValueData: 1; \
Flags: uninsdeletevalue
[Run]
Filename: "{app}\WinSCP.exe"; Description: "Launch &WinSCP"; \
Flags: nowait postinstall skipifsilent
[UninstallRun]
Filename: "{app}\WinSCP.exe"; Parameters: "/UninstallCleanup"; \
RunOnceId: "UninstallCleanup"
```
--------------------------------
### Full C# Example: Automating WinSCP with XML Logging
Source: https://winscp.net/eng/docs/guide_dotnet
A comprehensive C# example demonstrating how to start a WinSCP process, feed it commands, redirect I/O, wait for completion, and parse the resulting XML log for success or error messages and file information.
```csharp
using System;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
...
const string logname = "log.xml";
// Run hidden WinSCP process
Process winscp = new Process();
winscp.StartInfo.FileName = "winscp.com";
winscp.StartInfo.Arguments = "/xmllog=\"" + logname + "\" ";
winscp.StartInfo.UseShellExecute = false;
winscp.StartInfo.RedirectStandardInput = true;
winscp.StartInfo.RedirectStandardOutput = true;
winscp.StartInfo.CreateNoWindow = true;
winscp.Start();
// Feed in the scripting commands
winscp.StandardInput.WriteLine("option batch abort");
winscp.StandardInput.WriteLine("option confirm off");
winscp.StandardInput.WriteLine("open mysession");
winscp.StandardInput.WriteLine("ls");
winscp.StandardInput.WriteLine("put d:\\examplefile.txt");
winscp.StandardInput.Close();
// Collect all output (not used in this example)
string output = winscp.StandardOutput.ReadToEnd();
// Wait until WinSCP finishes
winscp.WaitForExit();
// Parse and interpret the XML log
// (Note that in case of fatal failure the log file may not exist at all)
XPathDocument log = new XPathDocument(logname);
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("w", "http://winscp.net/schema/session/1.0");
XPathNavigator nav = log.CreateNavigator();
// Success (0) or error?
if (winscp.ExitCode != 0)
{
Console.WriteLine("Error occured");
// See if there are any messages associated with the error
foreach (XPathNavigator message in nav.Select("//w:message", ns))
{
Console.WriteLine(message.Value);
}
}
else
{
// It can be worth looking for directory listing even in case of
// error as possibly only upload may fail
XPathNodeIterator files = nav.Select("//w:file", ns);
Console.WriteLine("There are {0} files and subdirectories:", files.Count);
foreach (XPathNavigator file in files)
{
Console.WriteLine(file.SelectSingleNode("w:filename/@value", ns).Value);
}
}
```
--------------------------------
### C# Example: Download Files with Session.GetFiles
Source: https://winscp.net/eng/docs/library_session_getfiles
Demonstrates how to connect to an SFTP server, download all files from a remote directory using a wildcard, and process the transfer results. Ensure you have WinSCP .NET Assembly installed and configured.
```csharp
using System;
using WinSCP;
class Example
{
public static int Main()
{
try
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Download files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult =
session.GetFiles("/home/user/*", @"d:\download\", false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Download of {0} succeeded", transfer.FileName);
}
}
return 0;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
return 1;
}
}
}
```
--------------------------------
### Full WinSCP .NET Assembly Example in Perl
Source: https://winscp.net/eng/docs/library_perl
A comprehensive example demonstrating WinSCP .NET assembly usage from Perl, including session setup, file upload, and result checking.
```perl
use strict;
use warnings;
use Win32::OLE;
use Win32::OLE::Const;
use Win32::OLE::Variant;
use constant
{
TRUE => Variant(VT_BOOL, 1),
FALSE => Variant(VT_BOOL, 0)
};
my $session = Win32::OLE->new('WinSCP.Session');
# Load constants
my $consts = Win32::OLE::Const->Load($session);
# Setup session options
my $sessionOptions = Win32::OLE->new('WinSCP.SessionOptions');
$sessionOptions->{'Protocol'} = $consts->{'Protocol_Sftp'};
$sessionOptions->{'HostName'} = 'example.com';
$sessionOptions->{'UserName'} = 'user';
$sessionOptions->{'Password'} = 'mypassword';
$sessionOptions->{'SshHostKeyFingerprint'} = 'ssh-rsa 2048 xxxxxxxxxxx...';
# Connect
$session->Open($sessionOptions);
# Upload files
my $transferOptions = Win32::OLE->new('WinSCP.TransferOptions');
$transferOptions->{'TransferMode'} = $consts->{'TransferMode_Binary'};
my $transferResult =
$session->PutFiles('d:\\toupload\\*', '/home/user/', FALSE, $transferOptions);
# Throw on any error
$transferResult->Check();
# Print results
my $items = Win32::OLE::Enum->new($transferResult->{'Transfers'});
my $item;
while (defined($item = $items->Next))
{
print $item->{'FileName'} . "\n";
}
```
--------------------------------
### Example: Set Local Directory to D Drive
Source: https://winscp.net/eng/docs/scriptcommand_lcd
This example demonstrates how to set the local working directory to the root of the D: drive.
```script
lcd d:\
```
--------------------------------
### Compile Inno Setup Script
Source: https://winscp.net/eng/docs/custom_distribution
Command to compile an Inno Setup script file using the Inno Setup compiler.
```bash
iscc winscpsetup.iss
```
--------------------------------
### Overall Example: Session, Upload, and Results
Source: https://winscp.net/eng/docs/library_examples
A comprehensive example demonstrating session creation, file upload, and checking/printing results. Suitable for understanding the basic workflow.
```C#
using System;
using WinSCP;
namespace WinSCP
{
class Program
{
static void Main(string[] args)
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "password",
// For SSH key authentication uncomment the following:
// SshHostKeyFingerprint = "ssh_host_key_fingerprint",
// PrivateKeyPath = "path_to_private_key_file"
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload file
session.PutFiles(@"C:\local\file.txt", "/remote/directory/", false).Check();
// Download file
session.GetFiles("/remote/directory/file.txt", @"C:\local\downloaded_file.txt").Check();
// Execute command
session.ExecuteCommand("ls -l").Check();
// Get file information
RemoteFileInfo fileInfo = session.Stat("/remote/directory/file.txt");
Console.WriteLine("Remote file '{0}' is {1} bytes.", fileInfo.FullName, fileInfo.Length);
// List directory
RemoteDirectoryInfo directoryInfo = session.ListDirectory("/remote/directory/");
Console.WriteLine("Directory listing of '{0}':", directoryInfo.FullName);
foreach (RemoteFileInfo file in directoryInfo.Files)
{
Console.WriteLine("- {0}", file.Name);
}
}
}
}
}
```
```VB.NET
Imports System
Imports WinSCP
Module Module1
Sub Main()
' Setup session options
Dim sessionOptions As New SessionOptions
sessionOptions.Protocol = Protocol.Sftp
sessionOptions.HostName = "example.com"
sessionOptions.UserName = "user"
sessionOptions.Password = "password"
' For SSH key authentication uncomment the following:
' sessionOptions.SshHostKeyFingerprint = "ssh_host_key_fingerprint"
' sessionOptions.PrivateKeyPath = "path_to_private_key_file"
Using session As New Session
' Connect
session.Open(sessionOptions)
' Upload file
session.PutFiles("C:\local\file.txt", "/remote/directory/", False).Check()
' Download file
session.GetFiles("/remote/directory/file.txt", "C:\local\downloaded_file.txt").Check()
' Execute command
session.ExecuteCommand("ls -l").Check()
' Get file information
Dim fileInfo As RemoteFileInfo = session.Stat("/remote/directory/file.txt")
Console.WriteLine("Remote file '{0}' is {1} bytes.", fileInfo.FullName, fileInfo.Length)
' List directory
Dim directoryInfo As RemoteDirectoryInfo = session.ListDirectory("/remote/directory/")
Console.WriteLine("Directory listing of '{0}':", directoryInfo.FullName)
For Each file As RemoteFileInfo In directoryInfo.Files
Console.WriteLine("- {0}", file.Name)
Next
End Using
End Sub
End Module
```
```PowerShell
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "example.com"
$sessionOptions.UserName = "user"
$sessionOptions.Password = "password"
# For SSH key authentication uncomment the following:
# $sessionOptions.SshHostKeyFingerprint = "ssh_host_key_fingerprint"
# $sessionOptions.PrivateKeyPath = "path_to_private_key_file"
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload file
$session.PutFiles("C:\local\file.txt", "/remote/directory/", $False).Check()
# Download file
$session.GetFiles("/remote/directory/file.txt", "C:\local\downloaded_file.txt").Check()
# Execute command
$session.ExecuteCommand("ls -l").Check()
# Get file information
$fileInfo = $session.Stat("/remote/directory/file.txt")
Write-Host "Remote file '$($fileInfo.FullName)' is $($fileInfo.Length) bytes."
# List directory
$directoryInfo = $session.ListDirectory("/remote/directory/")
Write-Host "Directory listing of '$($directoryInfo.FullName)':"
foreach ($file In $directoryInfo.Files)
{
Write-Host "- $($file.Name)"
}
}
finally
{
# Disconnect
$session.Dispose()
}
```
```JScript
var sessionOptions = new WinSCP.SessionOptions();
sessionOptions.Protocol = WinSCP.Protocol.Sftp;
sessionOptions.HostName = "example.com";
sessionOptions.UserName = "user";
sessionOptions.Password = "password";
// For SSH key authentication uncomment the following:
// sessionOptions.SshHostKeyFingerprint = "ssh_host_key_fingerprint";
// sessionOptions.PrivateKeyPath = "path_to_private_key_file";
var session = new WinSCP.Session();
try {
// Connect
session.Open(sessionOptions);
// Upload file
session.PutFiles("C:\\local\\file.txt", "/remote/directory/", false).Check();
// Download file
session.GetFiles("/remote/directory/file.txt", "C:\\local\\downloaded_file.txt").Check();
// Execute command
session.ExecuteCommand("ls -l").Check();
// Get file information
var fileInfo = session.Stat("/remote/directory/file.txt");
WScript.Log("Remote file '" + fileInfo.FullName + "' is " + fileInfo.Length + " bytes.");
// List directory
var directoryInfo = session.ListDirectory("/remote/directory/");
WScript.Log("Directory listing of '" + directoryInfo.FullName + "':");
for (var i = 0; i < directoryInfo.Files.length; i++) {
WScript.Log("- " + directoryInfo.Files[i].Name);
}
}
finally {
// Disconnect
session.Dispose();
}
```
```VBScript
Dim sessionOptions
Set sessionOptions = CreateObject("WinSCP.SessionOptions")
sessionOptions.Protocol = 2 ' SFTP
sessionOptions.HostName = "example.com"
sessionOptions.UserName = "user"
sessionOptions.Password = "password"
' For SSH key authentication uncomment the following:
' sessionOptions.SshHostKeyFingerprint = "ssh_host_key_fingerprint"
' sessionOptions.PrivateKeyPath = "path_to_private_key_file"
Dim session
Set session = CreateObject("WinSCP.Session")
On Error Resume Next
' Connect
session.Open sessionOptions
' Upload file
session.PutFiles "C:\local\file.txt", "/remote/directory/", False
session.Check
' Download file
session.GetFiles "/remote/directory/file.txt", "C:\local\downloaded_file.txt"
session.Check
' Execute command
session.ExecuteCommand "ls -l"
session.Check
' Get file information
Dim fileInfo
Set fileInfo = session.Stat("/remote/directory/file.txt")
MsgBox "Remote file '" & fileInfo.FullName & "' is " & fileInfo.Length & " bytes."
' List directory
Dim directoryInfo
Set directoryInfo = session.ListDirectory("/remote/directory/")
MsgBox "Directory listing of '" & directoryInfo.FullName & "':"
Dim file
For Each file In directoryInfo.Files
MsgBox "- " & file.Name
Next
' Disconnect
session.Dispose
Set session = Nothing
Set sessionOptions = Nothing
If Err.Number <> 0 Then
MsgBox "Error: " & Err.Description
End If
On Error GoTo 0
```
```VBA
Sub Main()
' Setup session options
Dim sessionOptions As New WinSCP.SessionOptions
sessionOptions.Protocol = WinSCP.Protocol.Sftp
sessionOptions.HostName = "example.com"
sessionOptions.UserName = "user"
sessionOptions.Password = "password"
' For SSH key authentication uncomment the following:
' sessionOptions.SshHostKeyFingerprint = "ssh_host_key_fingerprint"
' sessionOptions.PrivateKeyPath = "path_to_private_key_file"
Dim session As New WinSCP.Session
On Error Resume Next
' Connect
session.Open sessionOptions
' Upload file
session.PutFiles "C:\local\file.txt", "/remote/directory/", False
session.Check
' Download file
session.GetFiles "/remote/directory/file.txt", "C:\local\downloaded_file.txt"
session.Check
' Execute command
session.ExecuteCommand "ls -l"
session.Check
' Get file information
Dim fileInfo As WinSCP.RemoteFileInfo
Set fileInfo = session.Stat("/remote/directory/file.txt")
MsgBox "Remote file '" & fileInfo.FullName & "' is " & fileInfo.Length & " bytes."
' List directory
Dim directoryInfo As WinSCP.RemoteDirectoryInfo
Set directoryInfo = session.ListDirectory("/remote/directory/")
MsgBox "Directory listing of '" & directoryInfo.FullName & "':"
Dim file As WinSCP.RemoteFileInfo
For Each file In directoryInfo.Files
MsgBox "- " & file.Name
Next
' Disconnect
session.Dispose
Set session = Nothing
Set sessionOptions = Nothing
If Err.Number <> 0 Then
MsgBox "Error: " & Err.Description
End If
On Error GoTo 0
End Sub
```
```Perl
use strict;
use warnings;
use WinSCP;
# Setup session options
my $sessionOptions = WinSCP::SessionOptions->new();
$sessionOptions->Protocol(WinSCP::Protocol::Sftp);
$sessionOptions->HostName("example.com");
$sessionOptions->UserName("user");
$sessionOptions->Password("password");
# For SSH key authentication uncomment the following:
# $sessionOptions->SshHostKeyFingerprint("ssh_host_key_fingerprint");
# $sessionOptions->PrivateKeyPath("path_to_private_key_file");
my $session = WinSCP::Session->new();
# Connect
$session->Open($sessionOptions);
# Upload file
$session->PutFiles("C:\\local\\file.txt", "/remote/directory/", 0)->Check();
# Download file
$session->GetFiles("/remote/directory/file.txt", "C:\\local\\downloaded_file.txt")->Check();
# Execute command
$session->ExecuteCommand("ls -l")->Check();
# Get file information
my $fileInfo = $session->Stat("/remote/directory/file.txt");
print "Remote file '$($fileInfo->FullName)' is $($fileInfo->Length) bytes.\n";
# List directory
my $directoryInfo = $session->ListDirectory("/remote/directory/");
print "Directory listing of '$($directoryInfo->FullName)':\n";
foreach my $file ($directoryInfo->Files) {
print "- $($file->Name)\n";
}
# Disconnect
$session->Dispose();
```
```SSIS
// SSIS Package Example (Conceptual - requires WinSCP.dll reference and Script Task)
// This is a simplified representation. Actual implementation involves:
// 1. Adding WinSCP.dll as a reference in the Script Task.
// 2. Using the WinSCP COM object or .NET assembly.
// 3. Handling connection, transfer, and error logic within the script.
// Example using WinSCP .NET Assembly within an SSIS Script Task (C#):
/*
using System;
using System.IO;
using WinSCP;
public partial class ScriptMain : ScriptMain
{
public override void CreateNewOutputRows()
{
// ... (SSIS specific code for output variables) ...
}
public void Main()
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "password"
};
using (Session session = new Session())
{
try
{
session.Open(sessionOptions);
session.PutFiles(@"C:\\local\\file.txt", "/remote/directory/", false).Check();
// ... (further logic for SSIS variables, logging, etc.) ...
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
Dts.Events.FireError(0, "WinSCP Script Task", ex.Message, "", 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}
*/
// Note: Direct SSIS integration often involves custom components or more complex script tasks.
// The above is a conceptual C# snippet within a Script Task context.
```
--------------------------------
### Automating WinSCP Installation with Command-Line Parameters
Source: https://winscp.net/eng/docs/installation
Use these parameters with the WinSCP installer to automate the installation process, specifying language, silent installation, user scope, and logging.
```bash
WinSCP-Setup.exe /LANG=de /SILENT /ALLUSERS /LOG=winscp_install.log
```
--------------------------------
### Example Host Key Output
Source: https://winscp.net/eng/docs/guide_windows_openssh_server
This is an example of the output you can expect when retrieving host key fingerprints.
```text
C:\Windows\System32\OpenSSH>for %f in (%ProgramData%\ssh\ssh_host_*_key) do @%WINDIR%\System32\OpenSSH\ssh-keygen.exe -l -f "%f"
1024 SHA256:K1kYcE7GHAqHLNPBaGVLOYBQif04VLOQN9kDbiLW/eE martin@example (DSA)
256 SHA256:7pFXY/Ad3itb6+fLlNwU3zc6X6o/ZmV3/mfyRnE46xg martin@example (ECDSA)
256 SHA256:KFi18tCRGsQmxMPioKvg0flaFI9aI/ebXfIDIOgIVGU martin@example (ED25519)
2048 SHA256:z6YYzqGiAb1FN55jOf/f4fqR1IJvpXlKxaZXRtP2mX8 martin@example (RSA)
```
--------------------------------
### Example: Private Directory Listing
Source: https://winscp.net/eng/docs/message_unexpected_directory_listing
A common example of a directory listing format that WinSCP can parse.
```text
drw-r--r-- 3 martinp users 4596 2007-06-06 11:18:33.000000000 +0200 private
```
--------------------------------
### Start with Default Configuration
Source: https://winscp.net/eng/docs/commandline
Use `nul` as the path with the `/ini` parameter to force WinSCP to start with its default configuration and not save changes on exit.
```bash
winscp.exe /ini=nul
```
--------------------------------
### Session URL with Advanced Settings Example
Source: https://winscp.net/eng/docs/session_url
This example demonstrates how to include advanced settings, such as an HTTP proxy server, within a session URL.
```text
sftp://username:password;x-proxymethod=3;x-proxyhost=proxy@example.com/
```
--------------------------------
### Example XML Log File (log.xml)
Source: https://winscp.net/eng/docs/logging_xml
This is an example of an XML log file generated by a WinSCP session, containing download records.
```xml
```
--------------------------------
### Example of echo Command
Source: https://winscp.net/eng/docs/scriptcommand_echo
This example demonstrates how to use the echo command to inform the user about an ongoing file upload process.
```script
echo Uploading all report files...
```
--------------------------------
### Checksum Operation Example
Source: https://winscp.net/eng/docs/logging_xml
Provides an example of a 'checksum' operation, detailing the file, algorithm, and the resulting checksum.
```xml
```
--------------------------------
### PSFTP Script Example
Source: https://winscp.net/eng/docs/guide_psftp_script_to_winscp
This is an example of a PSFTP script file containing commands to open a connection, change directory, download files, close the connection, and quit.
```powershell
open user@example.com
cd /home/user
mget *.zip
close
quit
```
--------------------------------
### PSFTP Command Conversion Example
Source: https://winscp.net/eng/docs/guide_psftp_script_to_winscp
Example of converting a PSFTP command-line to its WinSCP equivalent, including script file and session parameters.
```WinSCP Script
winscp.com /script=script.txt
```
```WinSCP Script
open sftp://martin@example.com/ -password=password -hostkey="ssh-rsa 2048 aa:bb:cc:..."
```
--------------------------------
### Example WinSCP-specific URL with Save Extension
Source: https://winscp.net/eng/docs/integration_url
This example demonstrates how to use WinSCP-specific URL protocols combined with the save extension to store session settings. It includes a placeholder for the SSH host key fingerprint.
```text
winscp-sftp://martin:mypassword;fingerprint=ssh-rsa-xxxxxxxxxxx...@example.com/;save
```
--------------------------------
### Pageant: Run Another Program After Initialization
Source: https://winscp.net/eng/docs/ui_pageant
Use the -c option to have Pageant start another program after it has initialized and loaded keys. The started program can then use the loaded keys.
```bash
"C:\Program Files (x86)\WinSCP\PuTTY\pageant.exe" d:\main.ppk -c "C:\Program Files (x86)\WinSCP\WinSCP.exe"
```
--------------------------------
### Use -neweronly for Put and Get Commands
Source: https://winscp.net/eng/docs/history_old
The `-neweronly` switch for `put` and `get` scripting commands enables the 'New and updated files only' option, ensuring only changed files are transferred.
```bash
put -neweronly "local/path/*" "remote/path/"
```
```bash
get -neweronly "remote/path/*" "local/path/"
```
--------------------------------
### INI File Configuration for WinSCP
Source: https://winscp.net/eng/docs/custom_distribution
Example of an INI file structure for configuring WinSCP, including interface settings and a preconfigured 'Server' session. This can be installed by the installer.
```ini
[Configuration\Interface]
Interface=1
[Sessions\Server]
HostName=example.com
UserName=customer
Special=1
```
--------------------------------
### Command Syntax Example
Source: https://winscp.net/eng/docs/scripting
Illustrates the general syntax for WinSCP commands, including switches and parameters.
```WinSCP Script
command -switch -switch2 parameter1 parameter2 ... parametern
```
--------------------------------
### Example SSH Host Key Fingerprint Output
Source: https://winscp.net/eng/docs/guide_microsoft_azure
This is an example of the output you can expect when running the command to get SSH host key fingerprints. The exact set of key types may vary.
```text
256 SHA256:bKKCom8yh5gOuBNWaHHJ3rrnRXmCOAyPN/WximYEPAU /etc/ssh/ssh_host_ecdsa_key.pub (ECDSA)
256 SHA256:IYeDl+gseYk46Acg4g2mcXGvCr7Z8FqOd+pCJz/KLHg /etc/ssh/ssh_host_ed25519_key.pub (ED25519)
2048 SHA256:rA0lIXvHqFq7VHKQCqHwjsj28kw+tO0g/X4KnPpEjMk root@myazurevm (RSA)
```
--------------------------------
### VB.NET Example: Execute mysqldump and download
Source: https://winscp.net/eng/docs/library_session_executecommand
Demonstrates how to execute a mysqldump command to back up MySQL databases and then download the compressed dump file using WinSCP in VB.NET.
```vbnet
Imports WinSCP
Friend Class Example
Public Shared Function Main() As Integer
Try
' Setup session options
Dim sessionOptions As New SessionOptions
With sessionOptions
.Protocol = Protocol.Sftp
.HostName = "example.com"
.UserName = "user"
.Password = "mypassword"
.SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
End With
Using session As New Session
' Connect
session.Open(sessionOptions)
' Execute mysqldump on the server to dump all MySQL databases and
' compress the results
Const dbUsername As String = "USERNAME"
Const dbPassword As String = "PASSWORD"
Const tempFilePath As String = "/tmp/all_databases.gz"
Dim dumpCommand As String =
String.Format(
"mysqldump --opt -u {0} --password={1} --all-databases | gzip > {2}",
dbUsername, dbPassword, tempFilePath)
session.ExecuteCommand(dumpCommand).Check()
' Download the database dump
session.GetFiles(tempFilePath, "D:\dbbackup\").Check()
End Using
Return 0
Catch e As Exception
Console.WriteLine("Error: {0}", e)
Return 1
End Try
End Function
End Class
```
--------------------------------
### Resume Download (WinSCP)
Source: https://winscp.net/eng/docs/guide_psftp_script_to_winscp
WinSCP resumes SFTP transfers automatically. To explicitly resume a transfer, for example with an FTP protocol, use 'get -resume'.
```powershell
get -resume
```
--------------------------------
### Preconfigure WinSCP Site via Registry
Source: https://winscp.net/eng/docs/custom_distribution
Configures a WinSCP 'Server' session with hostname and username, and prevents user modification. This is added to the installer script.
```inno setup
[Registry]
#define RegistryKey "Software\Martin Prikryl\WinSCP 2"
; Configure hostname/username
Root: HKCU; SubKey: "{#RegistryKey}\Sessions\Server"; ValueType: string; \
ValueName: "HostName"; ValueData: "example.com"
Root: HKCU; SubKey: "{#RegistryKey}\Sessions\Server"; ValueType: string; \
ValueName: "UserName"; ValueData: "customer"
; Prevent user from accidentally deleting or modifing the session
Root: HKCU; SubKey: "{#RegistryKey}\Sessions\Server"; ValueType: dword; \
ValueName: "Special"; ValueData: 1
```
--------------------------------
### VB.NET Example: List Directory Contents
Source: https://winscp.net/eng/docs/library_session_listdirectory
Demonstrates how to connect to an SFTP server and list the contents of a remote directory, printing file details.
```vbnet
Imports WinSCP
Friend Class Example
Public Shared Function Main() As Integer
Try
' Setup session options
Dim sessionOptions As New SessionOptions
With sessionOptions
.Protocol = Protocol.Sftp
.HostName = "example.com"
.UserName = "user"
.Password = "mypassword"
.SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
End With
Using session As New Session
' Connect
session.Open(sessionOptions)
Dim directory As RemoteDirectoryInfo =
session.ListDirectory("/home/martin/public_html")
Dim fileInfo As RemoteFileInfo
For Each fileInfo In directory.Files
Console.WriteLine(
"{0} with size {1}, permissions {2} and last modification at {3}",
fileInfo.Name, fileInfo.Length, fileInfo.FilePermissions,
fileInfo.LastWriteTime)
Next
End Using
Return 0
Catch e As Exception
Console.WriteLine("Error: {0}", e)
Return 1
End Try
End Function
End Class
```
--------------------------------
### Display help for a specific command
Source: https://winscp.net/eng/docs/scriptcommand_help
Use the 'help' command followed by the command name to get detailed information about a specific script command. For example, 'help put' shows help for the 'put' command.
```script
help put
```
--------------------------------
### C# Example: Execute mysqldump and download
Source: https://winscp.net/eng/docs/library_session_executecommand
Demonstrates how to execute a mysqldump command to back up MySQL databases and then download the compressed dump file using WinSCP in C#.
```csharp
using System;
using WinSCP;
class Example
{
public static int Main()
{
try
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Execute mysqldump on the server to dump all MySQL databases and
// compress the results
const string dbUsername = "USERNAME";
const string dbPassword = "PASSWORD";
const string tempFilePath = "/tmp/all_databases.gz";
string dumpCommand =
string.Format(
"mysqldump --opt -u {0} --password={1} --all-databases | gzip > {2}",
dbUsername, dbPassword, tempFilePath);
session.ExecuteCommand(dumpCommand).Check();
// Download the database dump
session.GetFiles(tempFilePath, @"D:\dbbackup\").Check();
}
return 0;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
return 1;
}
}
}
```
--------------------------------
### PowerShell Example for Session.Open
Source: https://winscp.net/eng/docs/scriptcommand_open
This PowerShell snippet demonstrates how to configure SessionOptions and establish a connection using Session.Open, mapping parameters from a script's open command.
```PowerShell
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
# sftp://
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "martin"
Password = "mypassword"
# -hostkey
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
}
$session = New-Object WinSCP.Session
# Connect
$session.Open($sessionOptions)
```
--------------------------------
### Install OpenSSH Server Service (Manual Installation)
Source: https://winscp.net/eng/docs/guide_windows_openssh_server
Use this PowerShell command to install the sshd and ssh-agent services when manually installing OpenSSH on earlier Windows versions. Run this script as an Administrator.
```powershell
powershell.exe -ExecutionPolicy Bypass -File install-sshd.ps1
```
--------------------------------
### Example Batch File Execution
Source: https://winscp.net/eng/docs/script_auto_compress_download
This command demonstrates how to run the batch file to download all files matching `*.*` from the `/home/user/www` directory on the remote server.
```Batch
example.bat /home/user/www *.*
```
--------------------------------
### Create WinSCP Session using PowerShell Wrapper Module
Source: https://winscp.net/eng/docs/library_powershell
This example demonstrates creating a WinSCP session using the WinSCP PowerShell Wrapper module. It shows how to set credentials and connect to a host using SSH host key fingerprint.
```powershell
# Set credentials to a PSCredential Object.
$credential = Get-Credential
# Create a WinSCP Session.
$session = New-WinSCPSession -Hostname "example.com" -Credential $credential -SshHostKeyFingerprint "ssh-rsa 2048 xxxxxxxxxxx..."
```
--------------------------------
### Saving Installation Settings to a File
Source: https://winscp.net/eng/docs/installation
This command saves the current installation settings to an INI file, which can later be used with the /LOADINF parameter for automated installations.
```bash
WinSCP-Setup.exe /SAVEINF="winscp_settings.ini"
```
--------------------------------
### C# Example: List Directory Contents
Source: https://winscp.net/eng/docs/library_session_listdirectory
Demonstrates how to connect to an SFTP server and list the contents of a remote directory, printing file details.
```csharp
using System;
using WinSCP;
class Example
{
public static int Main()
{
try
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
RemoteDirectoryInfo directory =
session.ListDirectory("/home/martin/public_html");
foreach (RemoteFileInfo fileInfo in directory.Files)
{
Console.WriteLine(
"{0} with size {1}, permissions {2} and last modification at {3}",
fileInfo.Name, fileInfo.Length, fileInfo.FilePermissions,
fileInfo.LastWriteTime);
}
}
return 0;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
return 1;
}
}
}
```
--------------------------------
### Install WinSCP .NET Assembly to GAC
Source: https://winscp.net/eng/docs/library_install
Use this command to install the WinSCP .NET assembly into the Global Assembly Cache (GAC) on a development machine with the Windows SDK installed.
```bash
gacutil.exe /i WinSCPnet.dll
```
--------------------------------
### Example Extension Options Configuration
Source: https://winscp.net/eng/docs/extension
Illustrates the definition of various option types using @option metadata, including labels, links, textboxes, dropdownlists, file selectors, and checkboxes.
```text
# @option - -config label "Example extension options"
# @option - -config link https://winscp.net/eng/docs/extension#options
# @option Mask -config textbox "&File mask" "*.txt; *.html"
# @option SearchType -config dropdownlist "Search for:" -files ^
# -files="Files" -dirs="Directories" -both="Files and Directories"
# @option LogFile -config file "&Log File:" "%APPDATA%\mylog.log"
# @option Pause -config checkbox "&Pause at the end" -pause -pause
```
--------------------------------
### Cp Operation Example
Source: https://winscp.net/eng/docs/logging_xml
An example of a 'cp' operation, demonstrating the duplication of a remote file.
```xml
```
--------------------------------
### Example: Symbolic Link Listing
Source: https://winscp.net/eng/docs/message_unexpected_directory_listing
An example of a symbolic link entry in a directory listing.
```text
lrwxrwxrwx 1 martinp users 4 Mar 24 2005 wiki -> dokuwiki
```
--------------------------------
### Basic SFTP and FTP URLs
Source: https://winscp.net/eng/docs/session_url
Demonstrates basic SFTP and FTP URLs with username, password, and host. Includes examples with default and custom ports.
```plaintext
sftp://martin:mypassword@example.com/
```
```plaintext
sftp://root@example.com:2222/
```
```plaintext
ftp://127.0.0.1:2121/
```
--------------------------------
### Display Help Information
Source: https://winscp.net/eng/docs/commandline
The `/help` parameter displays usage information, providing an overview similar to the command-line documentation.
```bash
winscp.exe /help
```
--------------------------------
### List Supported Algorithms
Source: https://winscp.net/eng/docs/commandline
Use the `/info` parameter to list the supported SSH and TLS/SSL algorithms by WinSCP.
```bash
winscp.exe /info
```
--------------------------------
### Chmod Operation Example
Source: https://winscp.net/eng/docs/logging_xml
Shows an example of a 'chmod' operation, including recursive permission changes for a file.
```xml
```