问题:
之前一直使用sftp等软件进行服务器之间的文件传输,存在传输速度慢等缺点,因此尝试使用scp传输多个文件,发现大量重复工作,因此,考虑使用shell脚本来执行此操作。但是存在在进行scp操作时,需要远程服务器的密码?
解决方案:
1. 首先介绍一下scp远程传输文件操作。
scp -P port -r user@ip:/dir_name file_name
其中 port 表示远程服务器的的端口号
filename表示本机的文件路径
user表示远程服务器的用户名
ip表示远程服务器的IP地址
dir_name表示需要传输的文件绝对路径
2.了解好scp的用法之后,就需要写shell脚本文件
#!/bin/bash
remote_user="user_name"
remote_host="ip_addrest"
remote_port="port"
remote_path="file_path"
local_path="file_path"
subdirectories=("0050_02"....."your file names")
for subdir in "${subdirectories[@]}"; do
scp -P "$remote_port" -r "$remote_user@$remote_host:$remote_path/$subdir" "$local_path"
done
3.解决完shell脚本的问题之后,就需要解决远程服务器的密码问题。对于这个问题,考虑使用SSH密钥来解决。
3.1确保本地机器上有SSH密钥对,如果没有,可以使用命令来生成
ssh-keygen -t rsa
3.2将生成的公钥(一般在~/.ssh/id_rsa.pub
)添加到远程服务器的~/.ssh/authorized_keys
文件中
ssh-copy-id -p port user@ip address
3.3修改之前完成的shell脚本
#!/bin/bash
remote_user="user_name"
remote_host="ip_addrest"
remote_port="port"
remote_path="file_path"
local_path="file_path"
subdirectories=("0050_02"....."your file names")
for subdir in "${subdirectories[@]}"; do
scp -P "$remote_port"\
-r -i ~/.ssh/id_rsa \
"$remote_user@$remote_host:$remote_path/$subdir"\
"$local_path"
done
这样就可以批量的在服务器之间传输文件了!!!