248

If I'm logged in to a system via SSH, is there a way to copy a file back to my local system without firing up another terminal or screen session and doing scp or something similar or without doing SSH from the remote system back to the local system?

  • 4
    If you have an ssh server on your client you could always try scp file.foo user@myclient.com:file.foo :P – rahmu Nov 28 '11 at 20:22
  • 4
    For sure, but I don't want to allow access to my computer from a server owned by a company I work for :) I only have key-based authentication here anyway, and it wouldn't be too secure to put my private key up on the server! – Naftuli Kay Nov 28 '11 at 20:35
  • 2
    I don`t understand your problem. Generate a new key pair, copy the public part to your computers authorized_keys and after your transfer delete that line again. – Nils Nov 28 '11 at 21:48
  • 8
    I do this a lot, so it'd be inefficient to do this every time I want to copy a file in the middle of a SSH session. I'm just looking for a way, while in a SSH terminal session, to hook back to my local computer and have it send up a file to the remote server without having to leave the current SSH session. – Naftuli Kay Nov 28 '11 at 22:21
  • 1
    The issue is that the initial ssh login can be a pain (2fa or other challenges beyond key or password), we may not have the privs to change the ssh server's config, there is no reason to have to do key negotiation multiple times, and that once we have a session it would be nice to use that session for multiple things. – duanev Feb 4 '17 at 0:58
133

Master connection

It's easiest if you plan in advance.

Open a master connection the first time. For subsequent connections, route slave connections through the existing master connection. In your ~/.ssh/config, set up connection sharing to happen automatically:

ControlMaster auto
ControlPath ~/.ssh/control:%h:%p:%r

If you start an ssh session to the same (user, port, machine) as an existing connection, the second session will be tunneled over the first. Establishing the second connection requires no new authentication and is very fast.

So while you have your active connection, you can quickly:

Forwarding

On an existing connection, you can establish a reverse ssh tunnel. On the ssh command line, create a remote forwarding by passing -R 22042:localhost:22 where 22042 is a randomly chosen number that's different from any other port number on the remote machine. Then ssh -p 22042 localhost on the remote machine connects you back to the source machine; you can use scp -P 22042 foo localhost: to copy files.

You can automate this further with RemoteForward 22042 localhost:22. The problem with this is that if you connect to the same computer with multiple instances of ssh, or if someone else is using the port, you don't get the forwarding.

If you haven't enabled a remote forwarding from the start, you can do it on an existing ssh session. Type Enter ~C Enter -R 22042:localhost:22 Enter. See “Escape characters” in the manual for more information.

There is also some interesting information in this Server Fault thread.

Copy-paste

If the file is small, you can type it out and copy-paste from the terminal output. If the file contains non-printable characters, use an encoding such as base64.

remote.example.net$ base64 <myfile
(copy the output)
local.example.net$ base64 -d >myfile
(paste the clipboard contents)
Ctrl+D

More conveniently, if you have X forwarding active, copy the file on the remote machine and paste it locally. You can pipe data in and out of xclip or xsel. If you want to preserve the file name and metadata, copy-paste an archive.

remote.example.net$ tar -czf - myfile | xsel

local.example.net$ xsel | tar -xzf -
  • If we can transfer files using SSH, why do people still need/use SFTP? – Pacerier Oct 31 '14 at 15:55
  • 3
    @Pacerier Because SFTP is a way to transfer files using SSH. – Gilles Oct 31 '14 at 16:05
  • Why do people even need SFTP if they can transfer files using SSH-without-SFTP? – Pacerier Oct 31 '14 at 22:23
  • The copy-paste method is particularly convenient with chained connections (i.e. jumping through several hosts to reach the final one) – golimar Oct 7 '15 at 14:13
  • Last paragraph was a lifesaver. – noɥʇʎԀʎzɐɹƆ Aug 14 '16 at 21:19
63

Another (IMO) easy way would be:

# to remote host
cat localfile.conf | ssh user@hostname 'cat -> /tmp/remotefile.conf'

# from remote host
ssh user@hostname 'cat /tmp/remotefile.conf' > /tmp/localfile.conf

Or if you prefer something GUI-like, try Midnight Commander. They call the feature Shell-Link. Most distros have em in their package systems as mc.

  • 8
    Honestly, I don't understand why this isn't upvoted. OP asked for a solution without scp. Sometimes, particularly as in my case where I'm ssh'ing into a very crippled ISP-provided router, I don't have sftp, I don't have scp, and even ftp is badly broken. I knew I could do this, I just came here to make sure my syntax was right. – Auspex Jan 13 '16 at 21:13
  • 1
    Brilliant! mc is the quickest to use. – Namek Mar 9 '16 at 10:37
  • Yeah! Might be very lo-tech, but it also works right away. And sometimes that's all you need, rather than advice about installing package xyz that does it better. – JL Peyret May 28 '16 at 3:31
  • 1
    Actually, this solution does not work in my case. With a tunnel created from Windows to Linux, you start in putty, not a terminal. This method is exactly what I wanted, but I can't use it. Annoyed. – Benjamin May 15 '17 at 16:37
  • 1
    The reason I'm not upvoting this is because it won't work if the client machine is behind a shared router (like a corporate network). Supposed I'm on a work computer and I've ssh'd into my home server. How do I copy a file to my work computer having gone through the pains of cd'ing through complex directories with spaces and special characters? – user7000 Apr 2 '18 at 0:43
53

SSH does support a few commands, via the escape character (~ by default):

$ ~?
Supported escape sequences:
  ~.  - terminate connection (and any multiplexed sessions)
  ~B  - send a BREAK to the remote system
  ~C  - open a command line
  ~R  - Request rekey (SSH protocol 2 only)
  ~^Z - suspend ssh
  ~#  - list forwarded connections
  ~&  - background ssh (when waiting for connections to terminate)
  ~?  - this message
  ~~  - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)

$ ~C
ssh> help
Commands:
      -L[bind_address:]port:host:hostport    Request local forward
      -R[bind_address:]port:host:hostport    Request remote forward
      -D[bind_address:]port                  Request dynamic forward
      -KR[bind_address:]port                 Cancel remote forward
      !args                                  Execute local command

The !args seems to be closest to what you want. Note that you'll need to have PermitLocalCommand enabled in your /etc/ssh_config file in order for the ~C commands to work (see man ssh_config).

You can re-use the same ssh session if you set up a ControlMaster in ssh_config. If you do this:

$ ~C
ssh> !scp file user@myserver:

you've technically never left the ssh session, and don't need to re-authenticate. Probably more complicated than you'd like, but I can't think of another easy way.

  • Does this still work? I couldn't find !args in the help message. – xuhdev Jul 15 '16 at 5:04
  • @xuhdev it's still there on OpenSSH_7.2p2, args is not in the first help message (~?), but in the second (once one enters the ssh> prompt with ~C, one can type help at the ssh> prompt) – sdaau Sep 20 '17 at 8:59
  • This looks like a good solution (though I haven't tried it), I didn't realize you can get a parent command line buffer, vim-style. In practice, one might simply prefer to open a new terminal tab so that they don't forget how to get back into the session (like when I can never remember how to quit emacs). – user7000 Apr 2 '18 at 0:49
37

Those are all very complicated methods.
You can mount the remote file system on your local machine with sshfs:

mkdir -p /mnt/sshfs

root@IS1300:~# sshfs 192.168.1.2:/ /mnt/sshfs
root@IS1300:~# umount /mnt/sshfs

Then you can copy paste the file with nautilus, gnome, konqueror, dolphin, bash or whatever.

  • 4
    Connecting with a key-file: sshfs -oIdentityFile=~/.ssh/keyfile.pem user@192.168.1.2:/ /mnt/sshfs/ – sshow Sep 20 '15 at 12:23
15
  • Use ssh-xfer, a modified ssh-agent which effectively overloads an existing ssh side-channel for file-transfer use.
  • Use zssh, which is effectively zmodem over ssh. If you've ever used rzsz this will seem very familiar.
  • Reverse (-R, for remote-to-local) or forward (-L, for local-to-remote) ports to run file transfers over, assuming you have some file-transferring daemon listening on the other end.

But none of these are really needed, IMO. The SSH protocol supports multiple channels on a single connection, and the OpenSSH client supports multiplexing. Assuming you have ControlMaster and ControlPath set up (ControlPersist is useful too),

  # first connection
$ ssh remote

  # will multiplex over the same connection the original ssh opened
$ sftp remote
  • 5
    zmodem reminds me of the downloading the latest shareware from the local BBS.. :-) – Stuart Woodward Jun 8 '13 at 14:17
  • The xfer way is exactly what I was looking for, but do you know why the ssh-xfer patch is not included in the OpenSSH upstream? Some flame? – Ferran Basora Nov 13 '15 at 11:09
  • Thanks for zssh hint! I'm using tmux in Konsole and because of tmux my "sz" from server is not working anymore. The zssh solves my problems! – 0xAF May 5 at 20:13
9

An even simpler approach: Open Filezilla (or your favorite ftp browser), open an ssh connection to the same site, find the file and drag it across to your local file structure. If you're new to Filezilla, use the "site manager" feature to reconnect fast next time.

Yes, I know this is obvious to most of you (and not precisely on point), but some (like me) who found this thread searching for a terminal-only solution may have overlooked the obvious.

  • Yes, or sftp as suggested here. – atomicules Jul 13 '12 at 11:08
  • I believe FileZilla server is Windows only. Client is cross-platform though – Freedom_Ben Jul 24 '13 at 18:28
  • You could even use Caja, just open ssh://SERVER. – basic6 Mar 27 '17 at 18:35
8

What I've found to be the best and most efficient solution is to use xclip-copyfile and xclip-pastefile.

On the server, you use xclip-copyfile to copy one or more files. These files are then available on your local server. There, you can use xclip-pastefile.

This bypasses the need to use scp or have a local ssh server. I use this with cygwin for instance. The only problem is that this requires installing xclip if you don't already have it. Oh, and this works with binary files too.

  • Wow this might be a better solution than my reverse port forwarding plus netcat. – user7000 May 29 at 5:48
3

One of the many reasons we use SecureCRT — despite preferring open source software where practical — is the ease of doing file transfers. There simply is no direct replacement in the F/OSS world.

SecureCRT started out as a pure Windows program in the mid-1990s but was ported to Mac OS X and Linux a couple of years ago.

SecureCRT has three major features for transferring files to and from a system you are SSH'd into:

  • ZModem, YModem, XModem, Kermit and ASCII - SecureCRT is an old-school sort of terminal emulator, supporting several in-band file transfer protocols.

    The easiest to use is ZModem. When you type something like sz file-to-download on the remote command line, the remote sz program writes out an escape sequence that tells SecureCRT to immediately start downloading file-to-download to the default download directory.

    A nice touch is that the download directory is customizable per session. We use this to have per-site directories on our main office file server, so we don't have to manually sort downloaded files.

    (sz is the "send ZModem" program, part of the lrzsz package. It is packaged for most Unixy systems already. If for some reason your remote system doesn't have it installed already, and you can't easily install a binary package, the source package is small and highly portable. More than once, I've had to send an lrzsz "sharchive" or uuencode'd tarball to a stripped-down remote system so I could ZModem files to it.)

  • SFTP - SecureCRT has a tightly integrated basic SFTP implementation.

    By "tightly integrated," I mean that when you give the SFTP menu command or keyboard shortcut, it opens a new tab connected to the remote site over the same SSH connection. Thus, you don't need to log back in, and the connection is established a bit faster than if you had opened a separate SFTP connection to the same server.

    I characterize the SFTP feature as "basic," because VanDyke Software has a separate file transfer product, SecureFX. It is more featureful than the built-in SFTP client, and also integrates with SecureCRT.

    SecureCRT's SFTP feature lets you configure default remote and local directories which are separate from the ZModem configuration.

    This SFTP feature has a basic command line sort of interface, mimicking OpenSSH's sftp program, except that it has affordances like Tab command completion. Thus, retrieving a remote file called somefile.tar.gz might be as easy as get soTabEnter.

  • Drag-and-drop - If you drag-and-drop a file onto the terminal window, it automatically types rz for you and starts sending the file.

    Alternately, you can open an SFTP tab and drop a file onto that tab to send it via SFTP. Thus, sending a file to a remote system could be as simple as Alt-P, drag, drop.

    We find that transfers happen a lot faster via SFTP, probably because it's a TCP-based protocol, so it benefits from the large sliding windows of modern TCP/IP stacks. ZModem was designed in the days when a 64 kiB block size was considered "large." Thus, a lot of the potential speed in a link is soaked up in ZModem while each end waits for block transfer acknowledgements.

    One nice thing about the drag-and-drop mode of operation is that it takes one of the stresses out of using ZModem. When you type rz at the remote system, SecureCRT pops up a file picker automatically. You then have about a minute to find and select the file before the remote side times out. This creates a race-against-the-clock vibe that isn't pleasant. Drag-and-drop lets you find the file at your leisure, then start the transfer with a single quick motion of the mouse.

    We do still use the manual method, starting the transfer with an explicit rz command. This is because SecureCRT lets you configure a per-session upload directory, which we point at the folder on the file server that always contains the latest build of the software that particular remote site is running. For such transfers, there is no race against the clock, since the file picker opens in the correct place to start with.

1

Use "!" to convert the file to a ASCII-representation of your file (e.g. ! uuencode myfile.bin >uuencode.dat ). Then use ! cat uuencode.dat >target.dat. After that use uudecode on the target side: ! uudecode target.dat >myfile.bin

protected by Community Feb 4 '15 at 16:56

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.