How to ssh to vagrant without actually running “vagrant ssh”?

后端 未结 16 1372
清酒与你
清酒与你 2020-11-29 15:07

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

相关标签:
16条回答
  • 2020-11-29 15:42

    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

    0 讨论(0)
  • 2020-11-29 15:43

    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
    0 讨论(0)
  • 2020-11-29 15:47

    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
    
    0 讨论(0)
  • 2020-11-29 15:47

    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.

    0 讨论(0)
提交回复
热议问题