用 git 同步 Colab 与 Gitlab、Github 之间的文件

Colab 是谷歌提供的免费 Jupyter 服务,可使用 GPU。但由于每次的 VM (虚拟机)登出后所有文件都会连同VM被毁掉。如何将一个项目里的程序或数据同步到 Colab则往往比较麻烦。尽管谷歌盘也可以挂到 Colab 里用,但步骤也比较麻烦,另外 github 或 gitlab 的项目和谷歌盘的同步也并不直接。因而能直接将Colab 的 VM 与 github 或 gitlab 同步就可以节省时间。而且,程序在 Colab 上运行完后的结果也可以在VM消失前及时同步到github 或 gitlab 上保存。

用 git 同步Colab 与 gitlab、github 之间的文件共三步。

  • 生成 ssh 私钥-公钥对,将公钥添加到 gitlab 或 github 户头,私钥拷到系统剪贴板里备用。
    linux里可以用 ssh-keygen, Win里可以用 puttygen,github、gitlab 也可以生成私钥-公钥对。
    Linux 里的私钥-公钥对在 .ssh 里,私钥文件是 id_rsa, 公钥是 id_rsa.pub
    (github 户头添加公钥参考文档链接,gitlab户头添加公钥参考文档链接
  • 在colab里的 jupyter 里运行
    key = \
    '''
    私钥拷到这里
    '''
    ! mkdir -p /root/.ssh
    with open(r'/root/.ssh/id_rsa', 'w', encoding='utf8') as fh:
        fh.write(key)
    ! chmod 600 /root/.ssh/id_rsa
    ! ssh-keyscan gitlab.com >> /root/.ssh/known_hosts  # 这一步是将 gitlab.com 的指纹写到 .ssh/known_hosts 里,避免第一次运行时的yes/no交互
  • 然后就可以按正常 git 管理运作了:
    ! git ... 
    • 例:colab 同步 github
    1. 全局设置
      !git config --global user.email "addy@xyz.com"
      !git config --global user.name "your_name"
    2. 测试
      !ssh -T -o StrictHostKeyChecking=no git@github.com
      如果输出含‘Hi abc! You've successfully authenticated, but GitHub does not provide shell access.’ 则说明设置正确
      可以从github pull、push了。要注意 id_rsa 的 mod后6位必须为零(上面的
      ! chmod 600 /root/.ssh/id_rsa的目的)。
      设置不正确时,可以加 -v 或 -vv 看详情,例如:
      !ssh -vT -o StrictHostKeyChecking=no git@github.com

同样的思想可用于 rsync 同步 colab 和本机的文件。亲测可用。

    • !git config --global user.email "addy@xyz.com"
      !git config --global user.name "your_name"
    •  

posted @ 2018-09-01 00:20  mikeee  阅读(1918)  评论(0编辑  收藏  举报