【shell脚本】远程主机批量传输文件auto_scp.sh

这里还涉及到一个ssh的免密传输文件,需要进行配置才行。

注意:公钥相当于锁,私钥相当于钥匙,客户端创建一对钥匙和锁,要想做到SSH免密登录,就要将锁分发到服务器并装锁,然后客户端就可以利用这个钥匙开锁

建立SSH信任关系:

  • 生成秘钥(公钥和私钥)
# 切换到ssh目录
[root@rhel8 ~]# cd /root/.ssh/
[root@rhel8 .ssh]# ls
known_hosts

# 生成秘钥文件(一路回车即可)
[root@rhel8 .ssh]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
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:
SHA256:1eFqA0YG8GwTX/U+lGikRGWl+Zi7C/bEhpm4xJzxi5A root@rhel8.tourby.cn
The key‘s randomart image is:
+---[RSA 3072]----+
|    ..o.o.+o*..  |
|     o = o * * . |
|      = + o B +  |
|     . o o o *   |
|        S + o +  |
|       + * * . . |
|      E * B =    |
|       o + * .   |
|        o . +.   |
+----[SHA256]-----+
  • 将公钥拷贝到其他服务器上
[root@rhel8 .ssh]# ls
id_rsa  id_rsa.pub  known_hosts

# 这种方式会覆盖拷贝过去的服务器上的authorized_keys文件
[root@rhel8 .ssh]# scp -r id_rsa.pub root@IP地址:/root/.ssh/authorized_keys

# 这种不会覆盖,会追加。回车后输入密码即可
[root@rhel8 .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub ip地址

脚本内容:

[root@rhel8 shell]# vim auto_scp.sh 
#!/bin/bash
# auto scp files for client
# by authors tanbaobao 2020/06/09

FILES=$*

if [ -z $* ];then
        echo -e ‘\033[32mUsage: {$0 /boot|/tmp|file.txt}\033[0m‘
        exit
fi

for i in `echo IP地址1 IP地址2 ...`

do

        scp -r $FILES root@$i:/root/

done

 

【shell脚本】远程主机批量传输文件auto_scp.sh

上一篇:X-Cart 学习笔记(四)常见操作


下一篇:Linux常用命令3/3(有关系统管理的命令)--Unix/Linux操作系统05