Sunday, August 14, 2016

SCP (Secure Copy) Examples

temp

SCP (Secure Copy) Examples

Copy the file "foo.txt" from a remote host to the local host

$ scp you@remotehost.edu:foo.txt /local/dir

Copy the file "foo.txt" from the local host to a remote host

$ scp foo.txt you@remotehost.edu:/remote/dir

Copy the directory "foo" from the local host to a remote host's directory "bar"

$ scp -r foo you@remotehost.edu:/remote/dir/bar

Copy the file "foo.txt" from remote host "rh1.edu" to remote host "rh2.edu"

$ scp you@rh1.edu:/remote/dir/foo.txt you@rh2.edu:/remote/dir/

Copying the files "foo.txt" and "bar.txt" from the local host to your home directory on the remote host

$ scp foo.txt bar.txt you@remotehost.edu:~

Copy the file "foo.txt" from the local host to a remote host using port 2264

$ scp -P 2264 foo.txt you@remotehost.edu:/remote/dir

Copy multiple files from the remote host to your current directory on the local host

$ scp you@remotehost.edu:/remote/dir/\{a,b,c\} .
$ scp you@remotehost.edu:~/\{foo.txt,bar.txt\} .

SSH Cheatsheet

temp

SSH Notes

Configure aliases for hosts

For example, to set up named aliases for dev and qa, create a file at ~/.ssh/config:

Host dev
    HostName foo.somewhere.com
    User dev_username

Host qa
    HostName foo.somewhere.com
    User qa_usermname

Usage:

$ ssh dev

Passwordless auth with ssh-copy-id

Use ssh-copy-id to copy your public key to the remotehost. After you've logged in once, you get passwordless authentication thereafter.

$ ssh-copy-id -i ~/.ssh/id_rsa.pub remotehost

This will not work if you are connecting to a Windows remotehost.

Executing Multiple Commands with ssh

the here document syntax

The here document syntax lets you include everything in between << EOF and EOF as a list of commands. Like so:

$ ssh remotehost << EOF
  cd some_folder
  git pull
EOF

a script with commands only

Use a script of just the commands.

File: runner.sh

#!/usr/bin/env bash
cd some_project
./do_it.sh
ls

Use:

$ ssh user@remote 'bash -s' < /path/to/runner.sh

Transfer files with SFTP

You can use sftp in the same way ssh is used, to get an old-school ftp cli interface.

Compare files with diff

$ ssh user@host cat /path/to/remotefile | diff /path/to/localfile –

Port forwarding

Connects to a remote port, forward it to local.

$ ssh -L 4444:localhost:4000 remotehost

After that, from localhost, requests to http://localhost:4444 will get a response from http://remotehost:4000