How to ssh to vagrant without actually running "vagrant ssh"?
Asked Answered
E

17

190

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?

Eulogistic answered 2/6, 2012 at 17:16 Comment(3)
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.Menes
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!Birdsall
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.Piscatory
P
116

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
Piscatory answered 17/10, 2012 at 16:4 Comment(8)
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.Anchie
You could set the port on your own. Thus the script will be executable from any directory.Monomolecular
So, what is making that port a way to get in to the machine? Where is the configuration of what port it is?Artilleryman
Vagrant chooses an unused one with the auto_correct: true setting. Here's more info on how to change it manuallyPiscatory
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}') localhostReliquiae
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.Valuer
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.Goddaughter
vagrant ssh works fine as far as I can tell, what is thisCollier
Z
219

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
Zoophyte answered 15/5, 2014 at 17:58 Comment(6)
That is amazing. Mind adding vagrant-ssh file in .gitignore.Haydenhaydn
With some shells (e.g. zsh), the following one-liner works: ssh -F =(vagrant ssh-config) defaultKeyek
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 herePunak
Thanks @Punak this is the simplified way which also works for automated solutions where adding extra ssh parameter -F is not straightforwardAdalai
By adding an entry to the ~/.ssh/config in the way @Punak 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.Mcinerney
Great answer. Super easy. The only problem I had was my encoding was wrong. But a simple here took care of the problem. #55694354Riata
P
116

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
Piscatory answered 17/10, 2012 at 16:4 Comment(8)
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.Anchie
You could set the port on your own. Thus the script will be executable from any directory.Monomolecular
So, what is making that port a way to get in to the machine? Where is the configuration of what port it is?Artilleryman
Vagrant chooses an unused one with the auto_correct: true setting. Here's more info on how to change it manuallyPiscatory
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}') localhostReliquiae
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.Valuer
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.Goddaughter
vagrant ssh works fine as far as I can tell, what is thisCollier
O
72

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 [email protected] -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
Once answered 14/9, 2014 at 9:42 Comment(2)
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!Copp
So all you actually need is ssh vagrant@IP -p PORT -i path/to/privatekey. And that is even simpler than the top voted answerPolitician
P
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.

Perutz answered 3/1, 2013 at 16:26 Comment(2)
If you are using bash or zsh, process substitution is a simpler way of passing the output of one command to another. bash: ssh -F <(vagrant ssh-config) zsh: zsh process substitution ssh -F =(vagrant ssh-config) Dandiprat
@myshen: according to the answer by @tyrion process substitution doesn't work for ssh -F in bash - the way you mention should work in zsh though.Perutz
E
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 [email protected] -p 2222
Enrichetta answered 4/8, 2017 at 18:0 Comment(2)
nice! and note that typically, the password for the vagrant user is vagrantKingcup
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_keyPolitician
O
12

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
Octaviooctavius answered 24/8, 2019 at 7:19 Comment(0)
P
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.

Patriciate answered 20/12, 2013 at 11:50 Comment(0)
A
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
Abelmosk answered 17/7, 2014 at 21:58 Comment(0)
H
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 [email protected]

Hairston answered 25/6, 2016 at 23:45 Comment(0)
P
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 [email protected] -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.

Piccadilly answered 24/2, 2017 at 4:19 Comment(0)
B
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.

Bluefish answered 30/3, 2014 at 18:57 Comment(1)
Can I change a one machine config into a 2 machine config, if I make the old machine "primary"?Artilleryman
I
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 [email protected]

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

Intergrade answered 9/6, 2017 at 14:1 Comment(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.Integral
T
3

ssh vagrant@<host> password: vagrant

Examples:

Trey answered 10/11, 2017 at 11:22 Comment(0)
S
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.

Sucrase answered 23/3, 2018 at 18:5 Comment(0)
K
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
Kallick answered 9/9, 2013 at 2:7 Comment(0)
B
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.

Birmingham answered 12/11, 2016 at 7:38 Comment(0)
D
0
ssh [email protected] -i .vagrant/machines/default/virtualbox/private_key -p 2222
Dilute answered 30/4, 2024 at 10:1 Comment(1)
please provide details on what the command is doing and how this differs from the existing answersOletaoletha

© 2022 - 2025 — McMap. All rights reserved.