44

I want to copy a local file from a Vagrant machine to my localhost, but I am getting an error message:

ssh: connect to host 127.0.0.1 port 22: Connection refused.

[user@localhost ceil]$ scp -p 2222 vagrant@127.0.0.1:/home/vagrant/devstack/local.conf .
cp: cannot stat ‘2222’: No such file or directory
ssh: connect to host 127.0.0.1 port 22: Connection refused

I also tried using using localhost but still got the same error.

Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
geeks
  • 2,025
  • 6
  • 31
  • 49

7 Answers7

64

Another option is cat the files to something local:

vagrant ssh -c "sudo cat /home/vagrant/devstack/local.conf" > local.conf

This should also work for files that require root permissions (something the vagrant SCP plugin doesn't seem to support).

Jace Browning
  • 11,699
  • 10
  • 66
  • 90
40

You should read the manual page for scp. The correct syntax is:

scp -P 2222 vagrant@127.0.0.1:/home/vagrant/devstack/local.conf .

The uppercase P is for "port". Lowercase is used to preserve modification times.

Jakuje
  • 24,773
  • 12
  • 69
  • 75
  • 4
    copy file to vagrant machine : scp -i .vagrant/machines/your_machine_name/virtualbox/private_key -P 2222 /path/file vagrant@127.0.0.1: – Yi zhang Nov 22 '19 at 07:11
32

Get IdentityFile and Port by using

vagrant ssh-config

scp -i IdentityFile_file -P Port vagrant@127.0.0.1:/file_dir dist_dir e.g.

scp -i /Users/xxxxx/tmp/vagrant/centos_6.5/.vagrant/machines/default/virtualbox/private_key -P 2200  vagrant@127.0.0.1:/tmp/xxx .
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
SevenJ
  • 1,471
  • 2
  • 12
  • 7
11

As @SevenJ mentioned, ssh-config can provide all the info you need. But it's a lot easier to save it to a file and use that file, rather than constructing a complicated scp command. E.g.:

vagrant ssh-config > config.txt
scp -F config.txt default:/path/to/file .

Here I'm assuming your vagrant file doesn't override the machine name from "default". If it does, replace "default:" with ":".

Andy Lowry
  • 785
  • 7
  • 12
9

Another option like Dan linked to:

   vagrant plugin install vagrant-scp
   vagrant scp [vm_name]:<remote_path> <local_path

and if you need to do the opposite its

 vagrant scp <local_path> [vm_name]:<remote_path> 

You can use vagrant status to get the name of the VM

Current machine states:

default                   running (virtualbox)

Where default is the name of the VM in my case.

Dylan
  • 2,161
  • 2
  • 27
  • 51
5

This is a handy tool for anyone coming in via Google: Vagrant SCP

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Dan
  • 4,197
  • 6
  • 34
  • 52
0

Additional tools like scp or cat may not be necessary. Frederick Henri covered it here.

Essentially, cp [file] /var/www/[your vm]/.vagrant will copy the file to the .vagrant folder at your project root, where you can see and move the file in your desktop OS.

karolus
  • 912
  • 7
  • 13