ssh無密碼登入及遠端執行指令碼要使用公鑰與私鑰。linux下可以用用ssh-keygen生成公鑰/私鑰對,下面我以CentOS7為例。
測試環境:機器A(10.0.224.80);機器B(192.168.7.172)。現想A通過ssh免密碼在B上遠端執行命令。
1、首先在A機下生成公鑰/私鑰對:(-P表示密碼,-P '' 就表示空密碼,一次回車即可。在~/.ssh會生成id_rsa和id_rsa.pub兩個檔案)
[root@registry home]# ssh-keygen -t rsa -P '' Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): (直接回車) 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: e8:a1:c0:cc:d0:2c:88:82:35:0f:c7:75:2b:79:14:72 root@registry The key's randomart image is: +--[ RSA 2048]----+ | +...o E. | |++ =. * . | |B o . o o | |.* + | | = o S | | . o . | | . . | | | | | +-----------------+
[root@registry home]# cd ~/.ssh/
[root@registry .ssh]# ll
總用量 12
-rw-------. 1 root root 1675 4月 5 13:27 id_rsa
-rw-r--r--. 1 root root 395 4月 5 13:27 id_rsa.pub
-rw-r--r--. 1 root root 2492 4月 5 10:52 known_hosts
2、將A機下的id_rsa.pub複製到B機下
[root@registry .ssh]# scp ~/.ssh/id_rsa.pub root@192.168.7.172:/home root@192.168.7.172's password: id_rsa.pub 100% 395 0.4KB/s 00:00
3、在B機上,將從A機複製的id_rsa.pub新增到~/.ssh/authorzied_keys檔案裡,並賦予許可權
[root@CCC ~]# cat /home/id_rsa.pub >> ~/.ssh/authorized_keys [root@CCC ~]# chmod 600 ~/.ssh/authorized_keys
4、測試(注,第一次登入時需要手動輸入yes)
執行遠端命令
[root@registry home]# ssh root@192.168.7.172 "cd /home; ls" calico.tar laizy nagios ubuntu.tar [root@registry home]# ssh root@192.168.7.172 "ifconfig ens33" ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.7.172 netmask 255.255.255.0 broadcast 192.168.7.255 inet6 fe80::20c:29ff:fecd:7e7c prefixlen 64 scopeid 0x20<link> ether 00:0c:29:cd:7e:7c txqueuelen 1000 (Ethernet) RX packets 216165 bytes 20851014 (19.8 MiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 198202 bytes 19741868 (18.8 MiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 [root@registry home]#
免密碼,遠端登入
[root@registry home]# ssh root@192.168.7.172 Last login: Tue Apr 5 12:04:26 2016 from 192.168.7.146 [root@CCC ~]# ifconfig ens33 ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.7.172 netmask 255.255.255.0 broadcast 192.168.7.255 inet6 fe80::20c:29ff:fecd:7e7c prefixlen 64 scopeid 0x20<link> ether 00:0c:29:cd:7e:7c txqueuelen 1000 (Ethernet) RX packets 217411 bytes 20974871 (20.0 MiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 199328 bytes 19856521 (18.9 MiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0