185

I would like to reproduce the way Vagrant logs in to my VM within a shell script using an ssh command, so I create an alias to my Vagrant instance.

What is the command syntax to use the regular ssh command to access it?

Kevin Burke
  • 61,194
  • 76
  • 188
  • 305
  • What is it you're actually asking, I see three different things being asked, maybe you could expand the question then flag to migrate. Thanks. – Kev Jun 05 '12 at 22:48
  • 3
    By default the ssh port of VM which is -22 will be forwarded to 2222 on host machine. I putty-ed on 127.0.0.1 and port 2222 with SSH and it worked! – Vishal Biyani Jun 14 '12 at 17:14
  • 8
    If you're running more than one box, that port number will change automatically. You can get the right one by running `vagrant ssh-config`. – Stefano Palazzo Oct 17 '12 at 16:05

16 Answers16

207

There's a lot of answers already, but they all seem overly complicated or solve problems the asker didn't have.

simply:

# save the config to a file
vagrant ssh-config > vagrant-ssh

# run ssh with the file.
ssh -F vagrant-ssh default
Steven Soroka
  • 19,404
  • 4
  • 52
  • 40
  • 2
    That is amazing. Mind adding `vagrant-ssh` file in `.gitignore`. – sashaegorov May 02 '17 at 15:33
  • 7
    With some shells (e.g. `zsh`), the following one-liner works: `ssh -F =(vagrant ssh-config) default` – liori Aug 30 '17 at 16:17
  • 9
    You might want echo this result into your `ssh` config file: `vagrant ssh-config >> ~/.ssh/config` , so you just run `ssh default` from anywhere in your system, where `default` is the name of the VM that you can specify like [here](https://stackoverflow.com/a/20431791/5447286) – adamczi Sep 04 '18 at 19:32
  • Thanks @adamczi this is the simplified way which also works for automated solutions where adding extra ssh parameter `-F` is not straightforward – laimison Feb 02 '19 at 16:33
  • 3
    By adding an entry to the `~/.ssh/config` in the way @adamczi suggests you can then use the Visual Studio Code Remote - SSH extension to ssh into the Vagrant VM and edit files and do remote development. Simply CMD-SHIFT-P then "Remote-SSH: Connect to Host..." and the ssh .config entry you just added is automatically listed - you simply select it and voila, vscode connects to your remote vagrant vm! Without the config entry approach, I'm not sure how else I would have done it with vscode. – abulka Aug 03 '19 at 02:04
  • Great answer. Super easy. The only problem I had was my encoding was wrong. But a simple here took care of the problem. https://stackoverflow.com/questions/55693854/getting-bad-configuration-option-377-376h – Chris Mar 11 '22 at 12:09
114

I've had to re-implement "vagrant ssh" because it's -c option didn't pass on arguments properly. This is basically what it does (there might be more, but it works fine this way)

#!/bin/sh
PORT=$(vagrant ssh-config | grep Port | grep -o '[0-9]\+')
ssh -q \
    -o UserKnownHostsFile=/dev/null \
    -o StrictHostKeyChecking=no \
    -i ~/.vagrant.d/insecure_private_key \
    vagrant@localhost \
    -p $PORT \
    "$@"

As a one-liner (with thanks to kgadek):

ssh $(vagrant ssh-config | awk 'NR>1 {print " -o "$1"="$2}') localhost

To account for when you have more than one vagrant host, this will select the desired host, as well as cull blank lines from the config (using sed):

HOST=name-of-my-host
ssh $(vagrant ssh-config $HOST | sed '/^[[:space:]]*$/d' |  awk 'NR>1 {print " -o "$1"="$2}') localhost
Paul Chernoch
  • 5,275
  • 3
  • 52
  • 73
Stefano Palazzo
  • 4,212
  • 2
  • 29
  • 40
  • 5
    This answer doesn't let you `ssh` to your Vagrant from outside the `Vagrantfile` directory ("using the regular `ssh` command"), which is how I interpreted the question. – sjy Sep 04 '14 at 02:39
  • You could set the port on your own. Thus the script will be executable from any directory. – Yser Dec 15 '14 at 12:54
  • So, what is making that port a way to get in to the machine? Where is the configuration of what port it is? – nroose Oct 23 '15 at 17:45
  • 1
    Vagrant chooses an unused one with the `auto_correct: true` setting. Here's [more info on how to change it manually](http://oddessay.com/development-notes/changing-vagrants-default-ssh-port-to-prevent-collision-when-resuming-a-suspended-instance) – Stefano Palazzo Oct 23 '15 at 17:53
  • 1
    I had to skip first line, ie. the `Host` entry. The modified command is: `ssh $(vagrant ssh-config | awk 'NR>1 {print " -o "$1"="$2}') localhost` – kgadek Nov 20 '15 at 17:49
  • If your Vagrantfile defines multiple vagrant guest containers as mine does, this will not work. You need to change the code to select which host you intend to connect to. – Paul Chernoch Dec 16 '16 at 16:56
  • The one-liner was just what I needed. I am making a tmuxinator setup script that needs to log in to the same vagrant box on multiple panes, but `vagrant ssh` has a global lock - one process at a time only. `ssh` itself has no such lock, so using your one-liner let me bypass that limitation. – henrebotha Aug 04 '17 at 11:49
  • `vagrant ssh` works fine as far as I can tell, what is this – Andrew Koster Sep 21 '20 at 00:23
71

In terminal run

vagrant ssh

In another terminal window/tab run

ps aux | grep ssh

There you will see the actual command executed by Vagrant, something like this:

ssh vagrant@127.0.0.1 -p 2222 -o Compression=yes -o DSAAuthentication=yes -o LogLevel=FATAL -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -i ~/.vagrant.d/less_insecure_private_key -o ForwardAgent=yes
Leksat
  • 2,923
  • 1
  • 27
  • 26
  • Great trick if you need the host of your vagrant for ssh for other reasons, like a SQL GUI connection, such as Sequel Pro. This one save me! – Atomox Apr 06 '16 at 23:27
  • 1
    So all you actually need is `ssh vagrant@IP -p PORT -i path/to/privatekey`. And that is even simpler than the top voted answer – Aldian May 08 '22 at 09:11
20

Just pass the entire vagrant ssh-config as a config file to ssh with the -F configfile parameter. The host alias to connect to is defined on the first line in vagrant ssh-config; Host default means you can connect with ssh default.

I couldn't see an option to read the config file from the standard input, so went with the temp file route. Here's a one-liner that also cleans up the temporary $TMPDIR.vagrant-ssh-config file afterwards. It needs to be executed in the same directory as your Vagrantfile, assuming you vagrant box is up and running.

vagrant ssh-config > $TMPDIR.vagrant-ssh-config && ssh default -F $TMPDIR.vagrant-ssh-config ; rm $TMPDIR.vagrant-ssh-config

Note: on my Mac OSX system, $TMPDIR expands to /var/folders/46/yltlhtgx8m5cg68_w95wgvy41324gn/T/ (right now). Use another variable, or another folder, if it's not set on your system.

Community
  • 1
  • 1
Joel Purra
  • 24,294
  • 8
  • 60
  • 60
  • 3
    If you are using bash or zsh, [process substitution](http://tldp.org/LDP/abs/html/process-sub.html) is a simpler way of passing the output of one command to another. bash: `ssh -F <(vagrant ssh-config) ` zsh: [zsh process substitution](http://zsh.sourceforge.net/Intro/intro_7.html) `ssh -F =(vagrant ssh-config) ` – myeeshen Aug 07 '14 at 14:34
  • @myshen: according to [the answer by @tyrion](http://stackoverflow.com/a/20703044) process substitution doesn't work for `ssh -F` in bash - the way you mention should work in zsh though. – Joel Purra Dec 05 '14 at 11:52
18

I solved this in a very simple way: when you start the vagrant box it shows the ssh address like this

SSH address: 127.0.0.1:2222

then you can connect to the box by using the vagrant user, the host and the port you get

ssh vagrant@127.0.0.1 -p 2222
Samer Abu Gahgah
  • 751
  • 1
  • 9
  • 18
  • 3
    nice! and note that typically, the password for the vagrant user is `vagrant` – Brad Parks May 17 '18 at 13:54
  • it will only work if vagrant have added the ssh private key to your default ssh folder or else you will have to specify it in the command line. Which would make something like `ssh vagrant@IP -p PORT -i /home/USER/WORKING_REP/.vagrant/machines/default/libvirt/private_key` – Aldian May 08 '22 at 09:16
11

You can add vagrant host configuration to your local ssh config.

  1. vagrant ssh-config >> ~/.ssh/config

  2. ssh vagrant@{host}

ex. cat ~/.ssh/config

Host kmaster
  HostName 127.0.0.1
  User vagrant
  Port 2222..
  ....
  • ssh vagrant@kmaster
7

If you don't need to use stdin with ssh (for example you want to execute just a command and logout) you could use:

vagrant ssh-config --host default | ssh -F /dev/stdin default

This method was suggested in response to a similar question on google groups.

Unfortunately bash process substitution doesn't work either (see this question on unix.stackexchange for more details).

The best options you have, if you want an interactive shell, are to create a temp file and use that with ssh -F or use awk as suggested by the other answers.

Community
  • 1
  • 1
tyrion
  • 1,984
  • 1
  • 19
  • 25
5

If you just want to set it up so you can use normal the normal ssh commandline, as well as scp and such, you can run vagrant ssh-config and append the output to your default ssh configuration. If you replace the line "Host default" with a more descriptive hostname, you should be good to go.

vagrant ssh-config |sed -e "s/Host default/Host my_cool_dev_box/" >> ~/.ssh/config
ssh my_cool_dev_box
Tedward
  • 193
  • 3
  • 6
5

If you just want the bare minimum command to connect to your box, you need to know the port that it's using (printed when doing vagrant up, or visible doing vagrant ssh-config) and where's your private SSH key (also visible when doing vagrant ssh-config)

Then it's just a matter of providing the key and port:

ssh -p 2222 -i $HOME/vagrantenv/.vagrant/machines/default/virtualbox/private_key vagrant@127.0.0.1

Nico Villanueva
  • 876
  • 8
  • 22
5

A lot of the other answers assume you have Vagrant installed.

I have Vagrant installed on Windows 10, but I can't vagrant ssh because I'm using PuTTy as my SSH client, which vagrant won't accept.

The ssh executable found in the PATH is a PuTTY Link SSH client. Vagrant is only compatible with OpenSSH SSH clients.

However, in Windows 10 we also have Bash on Ubuntu on Windows. So, I just use that with the following command:

ssh vagrant@127.0.0.1 -p2222 -i .vagrant/machines/default/virtualbox/private_key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=Fatal

It's easy enough to install Vagrant on Win10-Ubuntu but it also wants you to install Virtualbox for some reason, which I'd rather not do.

N.B. I've tried with the ssh default -F vagrant-ssh-config method, but I just get

Permission denied (publickey,password).

I'm guessing this is because the IdentityFile path is a Windows path, whereas in Bash, it should begin with /mnt/c/. I suppose you could just write out the file and then modify it if that works better for you.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
3

Vagrant stores the private key in ~/.vagrant.d/insecure_private_key and uses it to connect to every machine through ssh, considering that it is configured to connect on port 2200 (default) it would be something like:

ssh vagrant@localhost -p 2200 -i ~/.vagrant.d/insecure_private_key

Note: make sure that the private key is owned by the user running Vagrant.

Though if your aim is to have a multi-machine environment you may do so using config.vm.define.

Here's an example illustrating an environment with 2 machines, one called web and the other is databases:

config.vm.define 'web', primary: true do |web|
        web.vm.box = 'CentOS64'
        web.vm.hostname = 'vic-develop'
        web.vm.network 'private_network', ip: '192.168.50.10', virtualbox__intnet: true
        web.vm.synced_folder '../code', '/var/www/project', :mount_options => ["dmode=777,fmode=777"]

        web.vm.provision 'ansible' do |ansible|
            ansible.playbook = 'development-web.yml'
            ansible.sudo = true
        end
end

config.vm.define 'databases' do |db|
    db.vm.box = 'CentOS64'

    db.vm.network 'private_network', ip: '192.168.50.20', virtualbox__intnet: true
    db.vm.network :forwarded_port, guest: 3306, host: 8206

    db.vm.provision 'ansible' do |ansible|
        ansible.playbook = 'development-db.yml'
        ansible.sudo = true
    end
end

Then you will have all Vagrant commands available per machine, i.e. vagrant ssh web and vagrant provision databases.

mulkave
  • 831
  • 1
  • 10
  • 22
  • Can I change a one machine config into a 2 machine config, if I make the old machine "primary"? – nroose Oct 23 '15 at 17:52
3

There is a way that replicates how a remote user might login to the system

  1. Edit the Vagrantfile for your instance adding in

config.vm.network "private_network", ip: "192.168.33.10"

This adds a private IP for the host (make it what you wish in the 192.168 range so long as its not already used

  1. Restart the instance with vagrant reload from the command line
  2. Copy the vagrant private_key file to some Linux equivalent you should have running on your box (e.g. Cygwin if on windows, I use windows 10) to your cygwin home directory, renaming it along the way to something describing the host the key is to be used for, e.g.

your_virtual_host_name.pem

  1. You'll find the key under .vagrant\machines\default\virtualbox\private_key

  2. Go to your home directory and do your usual Unix ssh, so

ssh -i your_virtual_hostname.pem username@192.168.33.10

where username, may well be vagrant if you have a standard box, look at the output of vagrant ssh-config for ssh standard details for the box.

That's it

Jimbo
  • 31
  • 1
  • Thank you, thanks to your idea of copying the key file from vagrant elsewhere I realized what problem I had - I used the **libvirt** provider on Linux. This is important because with libvirt provider you need to initialize **vagrant** with sudo and all files within the ```.vagrant``` folder are therefore owned by root. And permissions on the file were rw------- so only root had permissions to read the key file. Perhaps this might be helpful to anyone. – TomasH Apr 02 '19 at 20:14
3

ssh vagrant@<host> password: vagrant

Examples:

  • ssh vagrant@vagrant.local

  • or after checking the IP (from the inside, using vagrant ssh) ssh vagrant@172.28.128.3

Calamar
  • 1,547
  • 1
  • 13
  • 25
3

You can add ssh config for your vagrant host to ssh config.

  1. Get ssh config for vagrant machine in vagrant folder: vagrant ssh-config

  2. Open {UserDir}/.ssh/config and append there result from the previous command. Note: the first line Host default mean the alias which you will use later for ssh command. Name it as your vagrant machine or dir. If you have only one vagrant dir - you can name it Host vagrant

  3. Ssh to vagrant: ssh vagrant. The last name is alias from the previous step.

FreeLightman
  • 2,224
  • 2
  • 27
  • 42
1

You can take any of the ssh-config arguments, and pass them to ssh on the commandline as -o Key=value. So, for a simple one-host vagrant setup (you might have to do a little more work with grep or perl for a multihost setup), you can do something like the following (or replace perl with sed if you want):

ssh `vagrant ssh-config | tail -8 | perl -pe 's/^\s+/-o@/; s/\s/\=/;s/@/ /;s/\n/ /'` vagrant@localhost
Kyle Kanos
  • 3,257
  • 2
  • 23
  • 37
0

My Env. is Win7 + Centos. The answer with most agreement doesn't work for me. After failing after trying ssh -p [port] [usrname]@127.0.01 , I just use XShell to add a new session with the vagrant port and user name.

It works.

Maybe Xshell is a candinate.

onebraveman
  • 511
  • 7
  • 11