如何使用SSH连接到远程主机并创建一个Bash脚本,以将所有文件和文件夹从旧服务器复制到新服务器,以便每天进行备份?
首先,您需要生成一个ssh密钥。在您要连接的计算机上,运行:
$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/vidarlo/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/vidarlo/.ssh/id_rsa.
Your public key has been saved in /home/vidarlo/.ssh/id_rsa.
The key fingerprint is:
SHA256:/jxfxiWiao0m7YG9MiHgXBFKoo7kJcgTOrPtAZNtpVg [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|..E o. |
|=B.+. |
|@==. . |
|=O= . |
|o=oo S . . .|
| .o.. .+ . o o |
| . ..o+o. + |
| + =*o o |
| B+ oo. |
+----[SHA256]-----+
[~]$
询问时只需按Enter;默认位置,没有密码短语是可以的。
这将生成一个私钥和公钥。下一步是将公钥复制到远程服务器,以便可以使用它。ssh-copy-id
可以用于此:
$ ssh-copy-id user@host
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/vidarlo/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
user@host's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'user@host'"
and check to make sure that only the key(s) you wanted were added.
在这一阶段,您应该能够运行ssh user@host
,而无需输入密码即可登录。
您需要一个简单的scp。这是不好的,原因有几个:
但无论如何。只要您知道警告,就可以做到这一点。使用crontab -e
编辑您的crontab的用户。插入这样的一行:
0 5 * * * /usr/bin/scp "/path/to/backup" "user@remote:/path/to/store/backups"
该命令将在每晚05:00运行。如果您愿意,可以更改此设置。字段说明如下:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句