-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup_func2.py
94 lines (65 loc) · 2.21 KB
/
backup_func2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def backup_func2():
"""
Recursively backup all the files in a remote directory
"""
# information about the source sftp server
# and directories
hostname = 'ip'
port = 22
username = 'username'
password = 'password'
start_directory = 'dir in sftp to backup'
backup_dir = 'dir on the local machine to save to'
import paramiko
import os
import datetime
import discord
from discord.ext import commands
def get_files_directories():
file_list = sftp.listdir('.')
files = []
directories = []
for file_name in file_list:
try:
stat = str(sftp.lstat(file_name))
if stat[0] == 'd':
directories.append(file_name)
elif stat[0] == '-':
files.append(file_name)
except PermissionError:
print(('Skipping ' + file_name + ' due to permissions'))
return files, directories
def backup_directory(local_dir, remote_dir):
os.chdir(local_dir)
sftp.chdir(remote_dir)
print(('In directory ' + remote_dir))
files, directories = get_files_directories()
for f in files:
print(('Backing up ' + f))
try:
sftp.get(f, f)
except PermissionError:
print(('Skipping ' + f + ' due to permissions'))
for d in directories:
newremote = remote_dir + d + '/'
newlocal = local_dir + '\\' + d
os.mkdir(newlocal)
backup_directory(newlocal, newremote)
# Main program
# backup directories under here
os.chdir(backup_dir)
# Create directory with today's date
datestring = str(datetime.date.today())
os.mkdir(datestring)
os.chdir(datestring)
local_dir = os.getcwd()
# connect to sftp server
transport = paramiko.Transport((hostname, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
# back up everthing from top directory
remote_dir = start_directory
backup_directory(local_dir, remote_dir)
# quit sftp connection
sftp.close()
transport.close()