由于公司有了备份的需要,需要使用scp来自动的传输,所以我根据网上的很多资料研究了很久,最后写了一份满足我公司需要的scp自动传输文档,希望对大家有帮助。
环境:
发行版本RedHat5.4 X64位
为了大家看着方便,我把主机名给写出来
service:172.16.6.4 (nagios)
client:172.16.6.2 (savecenter)
1、服务端生产ssh密钥
[root@nagios .ssh]# ssh-keygen (所有选项一直回车即可) 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: 9a:b4:90:fd:86:7c:c9:88:b9:f0:f5:97:e6:98:2d:de root@nagios
可以查看是否有id_rsa(私钥)与id_rsa.pub(公钥)文件
[root@nagios tmp]# cd /root/.ssh [root@nagios .ssh]# ll total 12 -rw------- 1 root root 1675 Jan 31 13:21 id_rsa -rw-r--r-- 1 root root 393 Jan 31 13:21 id_rsa.pub -rw-r--r-- 1 root root 1399 Jan 27 14:01 known_hosts2、从服务端复制密钥到客户端
[root@nagios .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub 172.16.6.2 0 root@172.16.6.2's password: (输入客户端的root密码) Now try logging into the machine, with "ssh '172.16.6.2'", and check in: .ssh/authorized_keys (可以在客户端的/root/.ssh/里查看是否有authorized_keys 此文件,如果有就正常成功) to make sure we haven't added extra keys that you weren't expecting.3、自动传输脚本(可以自己随便命名,我使用的是scp.sh)
以下是脚本:
#! /bin/sh while getopts f: OPT; do case $OPT in f|+f) files="$OPTARG $files" ;; *) echo "usage: `basename $0` [-f hostfile] <from> <to>" exit 2 esac done shift `expr $OPTIND - 1` if [ "" = "$files" ] ;then echo "usage: `basename $0` [-f hostfile] <from> <to>" exit fi for file in $files do if [ ! -f "$file" ] ;then echo "no hostlist file:$file" exit fi hosts="$hosts `cat $file`" done for host in $hosts; do echo "do $host" scp -r $1 root@$host:$2 done其中第32行(scp -r $1 root@$host:$2 )如果不加参数r的话,传输文件夹的时候就会出现not a regular file问题,请记住,并给此脚本764权限(具体权限看你的需要)
[root@nagios .ssh]# chmod 764 scp.sh4、建立主机列表(client的列表,如果有多个客户端的话,每行是一个)
vim /root/.ssh/hostlist 172.16.6.25、在服务端执行scp.sh脚本,把文件传输到客户端
可以使用