1. 程式人生 > >Linux下的免密登陸

Linux下的免密登陸

介紹兩個命令

為什麼一上來就要介紹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] [email protected]

-i:指定公鑰檔案

實現免密登陸

[[email protected] ~]# 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 [email protected] The key's randomart image is: +--[ RSA 2048]----+ | .++o..+ | | .oo o = | | E o O | | O . | | * S . | | . * . | | o . | | . . | | . | +-----------------+

出現提示時預設就可以,這樣檔案就公鑰和私鑰就生成成功了

[[email protected] ~]# ls ~/.ssh/
id_rsa  id_rsa.pub

使用ssh-copy-id將公鑰釋出到遠端伺服器,會提示輸入密碼

[[email protected] ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
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.
[email protected]'s password: 
Now try logging into the machine, with "ssh '[email protected]'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

釋出完成進行測試,再次連線就無需密碼了

[[email protected] ~]# ssh [email protected]
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.