SCP命令传输文件及公私钥配置
一、scp命令
Linux scp 命令用于 Linux 之间复制文件和目录。scp 是 secure copy 的缩写, scp 是 linux 系统下基于 ssh 登陆进行安全的远程文件拷贝命令。
scp 是加密的,rcp 是不加密的,scp 是 rcp 的加强版。
写法及示例
scp [可选参数] file_source file_target
例如,想要从当前服务器向另一台服务器批量传输文件:
find /example/filePath -maxdepth 1 -type f -mtime -1655 -mtime +1290 -exec scp {} user@ip:/example/targetPath \;
其中:
/example/filePath
为要查找的目录路径。
-maxdepth 1
表示深度为1,即仅在当前目录下搜索。
-type f
表示搜索文件类型为普通文件。
-mtime -1655 -mtime +1290
表示文件修改时间在 1655 天到 1290天之间。
-exec scp {} user@ip:/example/targetPath \;
表示对于找到的每个文件执行 scp 命令进行上传,其中 {} 表示文件名占位符,; 表示命令结束符。
然而每传输一个文件都需输入目标server的密码,这时候需要进行SSH配置公钥私钥进行认证,从而免去此问题
二、使用SSH建立信任关系
1.首先在本地机器上生成公钥和私钥
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:
xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx root@localhost.domain
2.将公钥上传到另一台远程server
如下(示例)(带有重命名):
scp ~/.ssh/id_rsa.pub user@ip:~/.ssh/authorized_keys
完成此步后再进行之前的操作就不用重复输入密码了。
注意
如果server中已经存在authorized_keys文件,说明已经包含多个SSH验证信息,可用 cat >>命令将验证文件内容附加上去。
cat ~/.ssh/a.pub >> ~/.ssh/authorized_keys
此时就能将公钥添加到用户的授权密钥文件中,可以尝试重新运行原始命令来验证是否成功实现了 SSH 密钥认证。
参考:https://blog.csdn.net/weixin_28813401/article/details/116671202