python SSH SFTP 秘钥登陆
服务文件夹自动同步备份脚本
配置文件 .ini
[host]
private_key=E://id_rsa_4096
private_key_pass=23ewrwer
ip=192.1.1.1
username=root
remote_path=/root/vue
local_path=E://logs
private_key 私钥目录
private_key_pass 私钥密码
ip
username ssh用户名
remote_path 远程需要同步的目录
local_path 同步到本地的根目录,远程目录不变放在此根目录
python脚本
# -*- coding:UTF-8 -*-
import os
import sys
import time
from configparser import ConfigParser
from os.path import getsize
from stat import S_ISDIR, S_ISREG
import pysftp
print(time.strftime("开始文件夹同步------ %Y-%m-%d-%H:%M:%S", time.localtime()))
print(str(sys.argv))
conn = ConfigParser()
file_path = sys.argv[1]
if not os.path.exists(file_path):
raise FileNotFoundError("文件不存在")
conn.read(file_path)
# 配置文件
config_key = 'host'
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
# 读取配置
private_key = conn.get(config_key, 'private_key')
private_key_pass = conn.get(config_key, 'private_key_pass')
ip = conn.get(config_key, 'ip')
username = conn.get(config_key, 'username')
remote_path = conn.get(config_key, 'remote_path')
local_path = conn.get(config_key, 'local_path')
print(str(sys.argv))
sftp = pysftp.Connection(ip, username=username, private_key=private_key, private_key_pass=private_key_pass,
cnopts=cnopts)
def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
for entry in sftp.listdir(remotedir):
remotepath = remotedir + "/" + entry
localpath = os.path.join(localdir, entry)
print(remotedir)
print(localdir)
mode = sftp.stat(remotepath).st_mode
if S_ISDIR(mode):
try:
os.mkdir(localpath, mode=777)
except OSError:
pass
get_r_portable(sftp, remotepath, localpath, preserve_mtime)
elif S_ISREG(mode):
print(time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime()))
info = sftp.stat(remotepath)
print("远程文件", remotepath, '文件大小:', info.st_size)
exists = os.path.exists(localpath)
if not exists:
sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)
else:
local_file_size = getsize(localpath)
if local_file_size == info.st_size:
print(localpath, "存在,并未改变,不需要重新同步")
else:
print(localpath, "存在,已经改变,重新同步", local_file_size, info.st_size)
sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)
# remote_path = input("enter the remote_path: ")
# local_path = input("enter the local_path: ")
if __name__ == '__main__':
get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
运行方式
命令行运行:
python3 downlaod-params.py 'config13.ini'
Crontab定时执行 py命令同步