介绍两个命令
为什么一上来就要介绍ssh呢,因为直接使用ssh去连接远程电脑就更加能抛开图形化界面了,但是每次连接输入密码和远程主机名比较麻烦有什么好的解决方法呢?
ssh-keygen
ssh-keygen命令用于为“ssh”生成、管理和转换认证密钥,它支持RSA和DSA两种认证密钥。
使用方法: ssh-keygen [options]
-b:指定密钥长度;
-e:读取openssh的私钥或者公钥文件;
-C:添加注释;
-f:指定用来保存密钥的文件名;
-i:读取未加密的ssh-v2兼容的私钥/公钥文件,然后在标准输出设备上显示openssh兼容的私钥/公钥;
-l:显示公钥文件的指纹数据;
-N:提供一个新密语;
-q:静默模式;
-t:指定要创建的密钥类型。
ssh-copy-id
ssh-copy-id命令可以把本地主机的公钥复制到远程主机的authorized_keys文件上,ssh-copy-id命令也会给远程主机的用户主目录(home)和~/.ssh
, 和~/.ssh/authorized_keys
设置合适的权限。
使用方法: ssh-copy-id [option] remoteuser@romoteaddress
-i:指定公钥文件
实现免密登陆
[root@ashinlee ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again: r
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
46:41:b3:2e:36:c5:9c:ff:0a:0c:25:1b:10:5c:c2:b0 root@ashinlee
The key's randomart image is:
+--[ RSA 2048]----+
| .++o..+ |
| .oo o = |
| E o O |
| O . |
| * S . |
| . * . |
| o . |
| . . |
| . |
+-----------------+
出现提示时默认就可以,这样文件就公钥和私钥就生成成功了
[root@ashinlee ~]# ls ~/.ssh/
id_rsa id_rsa.pub
使用ssh-copy-id将公钥发布到远程服务器,会提示输入密码
[root@ashinlee ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@xx.xx.xxx.xxx
The authenticity of host 'xx.xx.xxx.xxx (xx.xx.xxx.xxx)' can't be established.
RSA key fingerprint is 39:0b:89:80:42:9e:21:45:f4:b8:13:d6:93:cc:44:06.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'xx.xx.xxx.xxx' (RSA) to the list of known hosts.
root@xx.xx.xxx.xxx's password:
Now try logging into the machine, with "ssh 'root@xx.xx.xxx.xxx'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
发布完成进行测试,再次连接就无需密码了
[root@ashinlee ~]# ssh root@xx.xx.xxx.xxx
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-117-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
New release '18.04.1 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
Welcome to Alibaba Cloud Elastic Compute Service !
配置别名
现在虽然不用每次都去输入密码来登陆了,但是想要去连接远程主机还需要记住ip地址,就算记得住还要每次都去打,好麻烦,下面介绍配置别名的方法
在.ssh目录中创建config文件按照以下格式配置即可
lixingdeMacBook-Pro:~ lixing$ vim ~/.ssh/config
Host aliyun # 连接的别名
HostName xx.xx.xxx.xxx # 远程主机
User root # 连接用户
Port 22 # 端口
进行测试, Perfect !
lixingdeMacBook-Pro:~ lixing$ ssh aliyun
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-117-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
New release '18.04.1 LTS' available.
Run 'do-release-upgrade' to upgrade to it.