SSH 无密码远程执行脚本

时间:2023-03-08 16:56:11

  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::::0f:c7::2b::: root@registry
The key's randomart image is:
+--[ RSA ]----+
| +...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 % .4KB/s :

  3、在B机上,将从A机复制的id_rsa.pub添加到~/.ssh/authorzied_keys文件里,并赋予权限

[root@CCC ~]# cat /home/id_rsa.pub >> ~/.ssh/authorized_keys
[root@CCC ~]# chmod ~/.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=<UP,BROADCAST,RUNNING,MULTICAST> mtu
inet 192.168.7.172 netmask 255.255.255.0 broadcast 192.168.7.255
inet6 fe80::20c:29ff:fecd:7e7c prefixlen scopeid 0x20<link>
ether :0c::cd:7e:7c txqueuelen (Ethernet)
RX packets bytes (19.8 MiB)
RX errors dropped overruns frame
TX packets bytes (18.8 MiB)
TX errors dropped overruns carrier collisions [root@registry home]#

    免密码,远程登录

[root@registry home]# ssh root@192.168.7.172
Last login: Tue Apr :: from 192.168.7.146
[root@CCC ~]# ifconfig ens33
ens33: flags=<UP,BROADCAST,RUNNING,MULTICAST> mtu
inet 192.168.7.172 netmask 255.255.255.0 broadcast 192.168.7.255
inet6 fe80::20c:29ff:fecd:7e7c prefixlen scopeid 0x20<link>
ether :0c::cd:7e:7c txqueuelen (Ethernet)
RX packets bytes (20.0 MiB)
RX errors dropped overruns frame
TX packets bytes (18.9 MiB)
TX errors dropped overruns carrier collisions