Transfer files with SCP
using SshSharp.Scp; adds SCP transfers to SshClient as extension methods. They run the server's scp program over an exec
channel (scp -t to receive, scp -f to send), as the classic scp command does.
When to use
- The server has no SFTP subsystem: some embedded systems, appliances and restricted shells offer only
scp. - Otherwise prefer SFTP: it can list, resume and change files, and does not depend on a program on the server.
Files
// using SshSharp.Scp;
await client.UploadFileAsync("report.csv", "/srv/reports/report.csv", cancellationToken: cancellationToken);
await client.DownloadFileAsync("/var/log/app.log", "app.log", cancellationToken: cancellationToken);
// An existing directory as the target keeps the other side's file name, as scp does.
await client.UploadFileAsync("report.csv", "/srv/reports/", cancellationToken: cancellationToken);
Streams
var json = Encoding.UTF8.GetBytes("""{ "feature": true }""");
using (var source = new MemoryStream(json))
{
await client.UploadAsync(source, "/etc/myapp/flags.json", cancellationToken: cancellationToken); // the length comes from the stream
}
using var destination = new MemoryStream();
await client.DownloadAsync("/etc/hostname", destination, cancellationToken: cancellationToken);
UploadAsync takes the length from the stream; for a stream that cannot seek, pass length:. SCP sends the length before the
data, so it must be known in advance.
Directories, permissions and progress
var options = new SshScpOptions
{
Preserve = true, // scp -p
FileMode = UnixFileMode.UserRead | UnixFileMode.UserWrite, // 0600 for files whose mode is not preserved
Progress = new Progress<SshScpProgress>(p => Console.Write($"\r{p.Path}: {p.BytesTransferred:N0}/{p.TotalBytes:N0}")),
};
await client.UploadDirectoryAsync("site", "/var/www/site", options, cancellationToken); // scp -r
await client.DownloadDirectoryAsync("/var/log/app", "logs", options, cancellationToken);
As with scp -r, the directory becomes the target when that does not exist, or goes inside it when it does.
Network devices and Windows servers
SCP runs scp -t <path> (or scp -f <path>) on the server, and by default writes the path as one single-quoted shell word:
scp -t -- '/srv/in box/report.csv', with any ', \ and ! escaped outside the quotes. That is safe for any path with the
shells sshd uses on Unix-like servers (sh, bash, zsh, fish, tcsh), but not on servers that read the line differently.
SshScpOptions.PathQuoting (new in 1.3) writes it for servers that read the line differently:
PathQuoting |
The line | For |
|---|---|---|
Posix (default) |
scp -t -- '/srv/in box/it'\''s.csv' |
Linux, BSD, macOS, and any server whose shell is sh, bash or zsh |
None |
scp -t flash:/acl-update.txt |
Network devices whose SCP server reads the line itself, with no shell: Cisco IOS, MikroTik RouterOS and others. The quotes would become part of the file name there |
DoubleQuote |
scp -t -- "C:\Reports\May 2024\report.csv" |
OpenSSH for Windows with its default shell, cmd.exe, which does not treat single quotes as quotes |
Network devices
// Cisco IOS and MikroTik RouterOS read "scp -t <path>" themselves, with no shell: send the path without quotes.
var device = new SshScpOptions { PathQuoting = SshScpPathQuoting.None };
// Cisco IOS (ip scp server enable): a file system prefix and a path.
await router.DownloadFileAsync("nvram:startup-config", "r1-startup-config.txt", device, cancellationToken);
await router.UploadFileAsync("acl-update.txt", "flash:/acl-update.txt", device, cancellationToken);
// MikroTik RouterOS: paths are relative to its file store.
await router.DownloadFileAsync("backup-2024-05.rsc", "backup-2024-05.rsc", device, cancellationToken);
None sends the path exactly as given, without -- (which some devices would take for the path). So that nothing on the line can
be split, taken for an option, expanded or run, it allows only letters, digits and / . _ - : + @ =, and not -, = or @
first; any other path throws ArgumentException before anything is sent. That covers device paths such as flash:/config.txt,
nvram:startup-config or disk0:/images/file.bin. A path with a space or a comma cannot be sent this way.
Windows servers
// OpenSSH for Windows runs the line through cmd.exe, which does not read single quotes: double-quote the path instead.
var cmd = new SshScpOptions { PathQuoting = SshScpPathQuoting.DoubleQuote };
await windows.UploadFileAsync("report.csv", @"C:\Reports\May 2024\report.csv", cmd, cancellationToken);
await windows.DownloadFileAsync("C:/Logs/app.log", "app.log", cmd, cancellationToken); // forward slashes work too
OpenSSH for Windows runs the line as cmd.exe /c "<line>", and scp.exe then splits it by the C runtime's rules. Inside double
quotes, spaces, &, ^, (, ), ; and ' are plain characters to both. DoubleQuote refuses, with ArgumentException and
before anything is sent, what they would still read:
- control characters (line breaks, tabs, escapes);
", which would end the word (no Windows name has one);%, whichcmd.exeexpands even inside double quotes (%USERPROFILE%), and!, which it expands there with delayed expansion;$and`, which PowerShell expands inside double quotes, so that a server whose default shell is PowerShell cannot run anything either (the mode is meant and tested forcmd.exe);- PowerShell's typographic double quotes (
“ ” „), and< > | * ?, which Windows does not allow in names; - a
\at the end, whichscp.exewould read, with the closing quote, as a literal". WriteC:\ReportsorC:/Reports/; - a
-first, which would be an option should the shell drop the--before the path (no Windows path starts with one).
CI runs the Windows mode against OpenSSH for Windows with cmd.exe as its shell.
Only paths you control
None and DoubleQuote put the path on a command line that something other than a POSIX shell reads. The checks above refuse
what could split the path or run a command, but a path from user input can still name any file the account can reach (..,
another drive). Give these modes paths your application builds, and use SFTP, which sends paths as data,
where the server offers it.
Notes and pitfalls
- Errors. A failed transfer (missing file, permission denied, no
scpon the server) throwsSshExceptionwithSshFailureReason.TransferFailedand the server's own message. - Quoting. By default, remote paths are passed to the server's shell as one single-quoted word, which is safe with sh, bash,
zsh, fish and tcsh.
A Windows server whose default shell is
cmd.exeor PowerShell does not read single quotes that way, and a network device reads them as part of the name: see Network devices and Windows servers. - Hostile servers. Every name the server sends must be one path component, and a single-file download accepts exactly one file, so a server cannot write outside the target or add files (CVE-2019-6111). Set-id and sticky bits are never applied.
- No resume, no listing. SCP has neither; use SFTP for those.
ScpCommand.SshScpOptions.ScpCommandnames the program to run on the server, whenscpis not on itsPATH.- Tracing. Each transfer is a span (
SshSharp.Scp.Upload,Download,UploadDirectory,DownloadDirectory) with the bytes it moved, andsshsharp.scp.bytescounts the file data; no path is recorded. See Tracing and metrics.
See also
- File transfer (SCP) (in-depth guide)
- Transfer files with SFTP
- SshScpExtensions in the API reference