0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ColabハックでGPUサーバーをVPSとして使おう

Last updated at Posted at 2025-04-20

MACユーザーーなのでColabでJupyterNoteBookを使っていますが
コードが長くなってくると、クラスにまとめたりライブラリを分割するリファクタリングをしたくなる事が多いです!
VSCodeを使ってコーディングするまでの手順を説明します

0. ssh-keyを作成

サーバー認証用のssh-keyを作成します

ssh-keygen -t rsa -b 4096 -m PEM -C "your_email@example.com"

1. ngrokでTokenを取得

NGROKはローカルPCやサーバー上で動くサービスを、外部から一時的に安全にアクセスできるようにするトンネリングサービスです。
Screenshot 2025-04-19 at 8.31.45.png

2. ColabのJupyterでVPSを起動

2.1 SSHとNgrokのセットアップ

!apt-get install -qq -o=Dpkg::Use-Pty=0 openssh-server
!pip install -q pyngrok

2.2 SSHサーバーインストール

openssh-server と 部トンネル用のpyngrok をインストールします

!mkdir -p /var/run/sshd
!echo 'PermitRootLogin yes' >> /etc/ssh/sshd_config
!echo 'PasswordAuthentication yes' >> /etc/ssh/sshd_config
!echo 'root:password' | chpasswd

2.3. 公開鍵をrootユーザーのauthorized_keysに設定

0で作成したローカルのid_rsa.pubの中身をサーバー側に保存します

!mkdir -p /root/.ssh
public_key = "*******"
with open("/root/.ssh/authorized_keys", "w") as f:
    f.write(public_key)

2.4. Ngrokでトンネリング

from pyngrok import conf, ngrok
conf.get_default().auth_token = ""*******""  # Ngrokのダッシュボードから取得
ssh_tunnel = ngrok.connect(22, "tcp")
print(ssh_tunnel)

2.5. リスタート

SSHサーバー設定の変更

!sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
!sed -i 's/^#\?ChallengeResponseAuthentication.*/ChallengeResponseAuthentication no/' /etc/ssh/sshd_config
!sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config
!service ssh restart

NgrokTunnel: "tcp://hoge.tcp.ngrok.io:fuga" -> "localhost:22"
のようなメッセージが出力されるので、ssh-configに宛先をコピーして利用します。
起動する度に変わるので注意が必要です。

3. ローカルのMACのssh-configの設定

Host colab-ssh
  HostName hoge.tcp.ngrok.io
  Port fuga
  User root
  IdentityFile *** # 1で作成したファイル

4. コマンドラインで接続

ssh colab-ssh

Screenshot_2025-04-19_at_8_40_07.png

無事に接続できました。

5. VSCodeからの利用

VsCodeのRemoteSSHプラグインをダウンロードしてインストールします

Screenshot 2025-04-20 at 11.01.26.png

6.終了

Colabのウィンドウを閉じるだけでは、ngrokは継続中になります
90分間操作がない場合にセッションタイムアウトしインスタンスは自動終了します
その場合に、GoogleDriveはアンマウントされるので再起動する必要があります
永続化したいデータは、GoogleDriveに保存するようにしましょう!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?