CentOS7免密码登录ssh和scp
在本地服务器生成SSH密钥
ssh-keygen
一路回车,会在root用户家目录下生成SSH私钥文件(id_rsa)和公钥文件(id_rsa.pub)
[root@UQL912175139 ~]# ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Created directory '/root/.ssh'. 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:VWQYWBMQuTp/Scl7LzfSpubQNATQ0sw8qBrm8cNOGFw root@UQL912175139 The key's randomart image is: +---[RSA 2048]----+ | . o. | |.o . . | |+. o . . o | | Eo o . + | | o o..S. | | o ..oO.o | | . . ..=*oo | | ..o *=@+ . | | .oo=+@+.o.. | +----[SHA256]-----+
生成之后会在用户的根目录生成一个 “.ssh”的文件夹,进入“.ssh”会生成以下几个文件
[root@UQL912175139 ~]# cd .ssh [root@UQL912175139 .ssh]# ls id_rsa id_rsa.pub
通过scp命令将内容写到异地服务器的/root/.ssh目录中
scp -rp ~/.ssh/id_rsa.pub username@remoteip:/root/.ssh/authorized_keys
#如果提示下面信息说明异地服务器上没有.ssh目录,去新建一个 scp: /root/.ssh/authorized_keys: No such file or directory #在异地服务器root目录下新建.ssh目录 mkdir /root/.ssh/
然后再重新执行scp上传命令后就成功将本地生成的id_rsa.pub公钥文件加入到了异地服务器的authorized_keys远程免密登录的公钥文件里面了,注意如果有多台主机想免密登录异地服务器只要隔行写入即可
例如:
ssh-rsa AAAABXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX== root@china-35238 ssh-rsa AAAABXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX== root@localhost
现在试试已经可以免密使用ssh和scp了
定时备份脚本
新建一个脚本文件backup.sh,将下面的代码复制进去
#!/bin/bash #打包网站备份文件上传到异地服务器,删除异地服务器里5天前的数据 ssh username@remoteip "find /root/backup -mtime +5 -name '*.*' -exec rm -Rf {} /;" tar zcvfP - /www/wwwroot/xxxx.com | ssh username@remoteip "cd /root/backup/; cat -> Web_$(date +%Y%m%d).tar.gz"
使用方法
crontab -e #每天早晨3点30执行一次备份脚本 30 03 * * * sh /root/backup.sh
linux系统下crontab更详细的使用方法《linux系统使用crond计划任务方法》
官方QQ群号码:922069959(空)、1093596563(空)