1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vagrantの仮想環境に素早くssh接続するPowershell関数

Last updated at Posted at 2024-09-30

動機

vagrant sshは遅い。.ssh/configに登録すると早くて良いけれど、ポート番号が変わるときもある。(僕はprivate_networkを登録してないし、sshの22番ポートのフォワーディングも使ってないです)

でも面倒じゃなく、素早くつなぎたかった。

解決策

ということで、VBoxManageをつかって必要な情報を取得して、sshでつなぐPowershellの関数を書いてみました。

  • grep、sedの代わりに ripgrepsd を使ってます。
function sshvm($vmname) {
  New-Variable -Name vmpath -Value (VBoxManage.exe showvminfo $vmname | rg 'Host path' | sd ".*path: '\\\\\?\\(.*)' .*" '$1')
  New-Variable -Name ip -Value (VBoxManage.exe showvminfo $vmname | rg 'ssh' | sd ".*host ip = ([\d\.]*),.*" '$1')
  New-Variable -Name port -Value (VBoxManage.exe showvminfo $vmname | rg 'ssh' | sd ".*host port = ([\d]*),.*" '$1')
  New-Variable -Name keypath -Value ".vagrant\machines\default\virtualbox\private_key"
  New-variable -Name user -Value 'vagrant'

  echo "ssh $user@$ip -p $port -i $vmpath\$keypath"
  ssh $user@$ip -p $port -i $vmpath\$keypath

  Remove-Variable -Name vmpath
  Remove-Variable -Name keypath
  Remove-Variable -Name ip
  Remove-Variable -Name port
  Remove-Variable -Name user
}

これを$profileかなにかに登録しておきます。sshvm でssh接続できます。

PS C:\> sshvm manjaro
ssh vagrant@127.0.0.1 -p 2200 -i D:\vagrant\manjaro\.vagrant\machines\default\virtualbox\private_key
Last login: Mon Sep 30 19:50:54 2024 from 10.0.2.2
[vagrant@manjaro ~]$
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?