1. 密钥生成

1.1 生成

执行下面的命令, 则一路回车回生成下面两个文件

  • id_rsa私钥
  • id_rsa.pub公钥
    1. ssh-keygen
    默认使用rsa算法, 也可以使用比较详细的命令, 如
    1. ssh-keygen -t ras -b 1024 -f yourkeyname -C "mark"
    | 参数 | 解释 | | —- | —- | | -b | 采用长度1024bit的密钥对,b=bits,最长4096,不过没啥必要 | | -t rsa | 采用 rsa 加密方式 | | -f | 生成文件名, f=output_keyfiles | | -C | 备注, C=comment |

更多参数可查看 man ssh-keygen

1.2 传递公钥到远程服务器

使用内置命令

  1. ssh-copy-id admin@mac.com

或者登录到远程服务器后,执行

  1. cat id_rsa.pub >> ~/.ssh/authorized_keys
  2. chmod 600 ~/.ssh/authorized_keys
  3. chmod 700 ~/.ssh

1.3 服务器ssh配置

修改服务上的 ssh配置文件 /etc/ssh/sshd_config

  1. RSAAuthentication yes
  2. PubkeyAuthentication yes
  3. PermitRootLogin no //禁止root登录
  4. PasswordAuthentication yes //允许密码登录,根据你的情况设置

配置完成后,重启服务

  1. service sshd restart

2. 连接服务器

2.1 配置文件 config (推荐)

配置文件生成在路径 .ssh/config, 里面可以存放每个链接的别名及链接所需信息, 如下面的典型配置

  1. Host api.alias
  2. Port 22
  3. User test
  4. HostName test.api.com
  5. IdentityFile ~/.ssh/id_rsa.yc

使用

  1. ssh api.alias

2.2 直接

  1. ssh -i ~/.ssh/id_rsa -p 22 user@yourservername