SSH 无密码远程执行脚本
Posted 振宇要低调
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSH 无密码远程执行脚本相关的知识,希望对你有一定的参考价值。
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两个文件)
[[email protected] 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 [email protected] The key‘s randomart image is: +--[ RSA 2048]----+ | +...o E. | |++ =. * . | |B o . o o | |.* + | | = o S | | . o . | | . . | | | | | +-----------------+
[[email protected] home]# cd ~/.ssh/
[[email protected] .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机下
[[email protected] .ssh]# scp ~/.ssh/id_rsa.pub [email protected]192.168.7.172:/home [email protected]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文件里,并赋予权限
[[email protected] ~]# cat /home/id_rsa.pub >> ~/.ssh/authorized_keys [[email protected] ~]# chmod 600 ~/.ssh/authorized_keys
4、测试(注,第一次登录时需要手动输入yes)
执行远程命令
[[email protected] home]# ssh [email protected]192.168.7.172 "cd /home; ls" calico.tar laizy nagios ubuntu.tar [[email protected] home]# ssh [email protected]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 [[email protected] home]#
免密码,远程登录
[[email protected] home]# ssh [email protected]192.168.7.172 Last login: Tue Apr 5 12:04:26 2016 from 192.168.7.146 [[email protected] ~]# 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
以上是关于SSH 无密码远程执行脚本的主要内容,如果未能解决你的问题,请参考以下文章