美文网首页首页投稿(暂停使用,暂停投稿)
利用 ssh 的用户配置文件 config 管理 ssh 会话

利用 ssh 的用户配置文件 config 管理 ssh 会话

作者: 技术学习 | 来源:发表于2016-07-21 10:38 被阅读1921次

    背景

    上次写的我在Deepin Linux 上使用ssh问题集锦日记中提到可以用config来方便管理ssh会话,现补充上来。

    介绍

    通常利用 ssh 连接远程服务器,一般都要输入以下类似命令:

    ssh user@hostname -p port
    

    如果拥有多个 ssh 账号,特别是像我这种喜欢在终端里直接 ssh 登陆,又不用 PuTTYSecureCRT之类的 ssh 客户端的,要记住每个ssh 账号的参数,比较浪费精力、时间。
      还好 ssh 提供一种优雅且灵活的方式来解决这个问题,就是利用 ssh 的用户配置文件 config 管理 ssh 会话。ssh 的用户配置文件是放在当前用户根目录下的 .ssh 文件夹里(~/.ssh/config,不存在则新创建一个),其配置写法如下:

    Host 别名
    HostName 主机名
    Port 端口
    User 用户名
    IdentityFile 密钥文件的路径
    IdentitiesOnly 只接受SSH key 登录
    PreferredAuthentications 强制使用Public Key验证

    提示:可以通过 man ssh_config,查看~/.ssh/config的语法。


    进入相关的配置后,就可以这样用 ssh 登陆服务器了:

    ssh 别名
    

    配置

    ➜ tonny@tonny-pc  ~/ssh  cp 115.29.240.144.pem ~/.ssh
    ➜ tonny@tonny-pc  ~/ssh  vi ~/.ssh/config 
    # snails
    Host snails
        HostName 115.29.240.144
        Port 63210
        IdentityFile ~/.ssh/115.29.240.144.pem
    ➜ tonny@tonny-pc  ~/ssh  ssh snails
    

    延伸阅读

    github/gitlab/bitbucket 管理多个ssh key

    以前只使用一个 ssh key 在github上提交代码,由于工作原因,需要再添加一个ssh key在公司的 gitlab上提交代码,下面记录下配置过程,防止遗忘。

    1. 针对github及gitlab分别生成公钥和私钥
    ➜ tonny@tonny-pc  ~/ssh  ssh-keygen -t rsa -C "luohoufu@company.com" -f ~/.ssh/id_rsa.gitlab
    ➜ tonny@tonny-pc  ~/ssh  ssh-keygen -t rsa -C "luohoufu@163.com" -f ~/.ssh/id_rsa.github
    
    • 添加私钥
    ➜ tonny@tonny-pc  ~/ssh ssh-add ~/.ssh/id_rsa.gitlab
    ➜ tonny@tonny-pc  ~/ssh ssh-add ~/.ssh/id_rsa.github
    ➜ tonny@tonny-pc  ~/ssh ssh-add -l
    

    ssh-add命令参考: ssh-add

    • 修改配置文件
    ➜ tonny@tonny-pc  ~/ssh  vi ~/.ssh/config
    # gitlab
    Host gitlab.com 
    HostName gitlab.com 
    PreferredAuthentications publickey 
    IdentityFile ~/.ssh/id_rsa.gitlab
      
    # github
    Host github.com 
    HostName github.com 
    PreferredAuthentications publickey 
    IdentityFile ~/.ssh/id_rsa.github
    
    • github密钥配置
    ➜ tonny@tonny-pc  ~/ssh xclip -sel clip < ~/.ssh/id_rsa.github.pub
    

    登录github.com,并点击左侧的SSH and GPG keys;然后点击“New SSH key” 并粘贴剪切板中的公钥;最后点击“Add SSH key”保存公钥。

    • 测试
    ➜ tonny@tonny-pc  ~/ssh ssh -T git@github.com
    Hi luohoufu! You've successfully authenticated, but GitHub does not provide shell access.
    #表示成功的连上github了,然后再在gitlab上进行同样的操作即可。
    

    相关文章

      网友评论

        本文标题:利用 ssh 的用户配置文件 config 管理 ssh 会话

        本文链接:https://www.haomeiwen.com/subject/mikbjttx.html