-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdripbox.py
236 lines (207 loc) · 7.66 KB
/
dripbox.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Eric Allen
#
# Author: Eric Allen <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Dripbox: Keep remote copy of directory tree in sync with local tree
import sys
import os
import re
import logging
import time
import getpass
import subprocess
import socket # to catch socket errors
import errno
import paramiko
import fsevents
from fsevents import Observer, Stream
SSH_KEY = os.path.join(os.environ['HOME'], ".ssh", "id_rsa")
SSH_CONFIG = os.path.join(os.environ['HOME'], ".ssh", "config")
LOCAL_PATH = os.getcwd()
log = logging.getLogger("dripbox")
# globals
remote_root = None
sftp_client = None
def _get_ssh_config_port(host):
if not os.path.exists(SSH_CONFIG):
return None
ssh_config = paramiko.SSHConfig()
try:
with open(SSH_CONFIG, 'r') as cfile:
ssh_config.parse(cfile)
except OSError, e:
log.error("Could not open SSH config: %s", str(e))
return None
except Exception, e:
log.error("Problem parsing SSH config: %s %s", type(e), str(e))
return None
port = ssh_config.lookup(host).get('port')
port = port and int(port)
return port
def rsync(remote, host, port=None, sync=False):
if not port:
port = _get_ssh_config_port(host) or 22
if sync:
command = ["rsync", "--delete", "-rltvze", "ssh -p%s" % port,
"--exclude", ".git", ".", remote]
subprocess.check_call(command)
else:
command = ["rsync", "--delete", "-crnltvze", "ssh -p%s" % port,
"--exclude", ".git", ".", remote]
diff = subprocess.Popen(command, stdout=subprocess.PIPE)
output, _ = diff.communicate()
for line in output.split("\n"):
if line == "":
pass
elif line == "sending incremental file list":
pass
elif re.match("sent \d+ bytes +received \d+ bytes [0-9\.]+ bytes/sec", line):
pass
elif re.search("total size is \d+ +speedup is [0-9\.]", line):
pass
else:
print output
print "WARNING: The remote tree is out of sync with the local tree. This is a dangerous situation."
print "Run dripbox with -f if you know what you're doing and want to run dripbox anyway"
print "We recommend you use --sync instead."
raise SystemExit(1)
def launch(username_p, host_p, remote_path, port_p=None):
global remote_root, sftp_client, username, host, port
username = username_p
host = host_p
port = port_p
remote_root = remote_path
sftp_client = setup_transport(username, host, port)
dirs_to_watch = [entry for entry in os.listdir(LOCAL_PATH) if
os.path.isdir(entry) and not entry.startswith(".")]
watch_files(dirs_to_watch)
def get_ssh_keys():
agent = paramiko.Agent()
if len(agent.get_keys()) > 0:
return agent.get_keys()
try:
return [paramiko.RSAKey.from_private_key_file(SSH_KEY)]
except paramiko.PasswordRequiredException:
passwd = getpass.getpass("Enter passphrase for %s: " % SSH_KEY)
try:
return [paramiko.RSAKey.from_private_key_file(filename=SSH_KEY,
password=passwd)]
except paramiko.SSHException:
print "Could not read private key; bad password?"
raise SystemExit(1)
def setup_transport(username, host, port=None):
if not port:
port = _get_ssh_config_port(host) or 22
for key in get_ssh_keys():
try:
transport = paramiko.Transport((host, port))
transport.connect(username=username, pkey=key)
break # key worked, continue
except socket.gaierror, e:
sys.stderr.write("Couldn't connect to %s:%s (%s)\n"
% (host, port, str(e)))
raise SystemExit(1)
except paramiko.AuthenticationException:
continue # try another key
else:
log.error("No SSH keys authenticated")
raise SystemExit(2)
client = paramiko.SFTPClient.from_transport(transport)
client.get_channel().settimeout(5)
return client
def reconnect():
log.warn("Re-connecting")
global sftp_client, username, host, port
sftp_client = setup_transport(username, host, port)
def is_temp_file(path):
if path.endswith(".swp"):
return True
if path.endswith("~"):
return True
if path.startswith(".#"):
return True
return False
def update_file(event):
global remote_root, sftp_client
full_path = event.name
if is_temp_file(full_path):
return
# Trying to sync git stuff can put remote repo into a really weird state
if ".git" in full_path:
return
mask = event.mask
truncated_path = full_path.replace(LOCAL_PATH, "")
remote_path = remote_root + truncated_path
try:
if mask & fsevents.IN_DELETE:
log.info("Deleting %s" % full_path)
try:
if os.path.isdir(full_path):
sftp_client.rmdir(remote_path)
else:
sftp_client.remove(remote_path)
except IOError:
log.info("File was already deleted")
else:
if os.path.isdir(full_path):
log.info("Creating directory %s" % remote_path)
try:
sftp_client.mkdir(remote_path)
except IOError:
log.info("Directory already exists")
else:
log.info("Uploading %s to %s" % (full_path, remote_path))
try:
sftp_client.put(full_path, remote_path)
except EOFError, e:
log.warn("Couldn't upload file")
time.sleep(0.1)
sftp_client.put(full_path, remote_path)
except OSError, e:
log.warn("Couldn't upload file")
time.sleep(0.1)
try:
sftp_client.put(full_path, remote_path)
except OSError, e:
log.exception("Failed to upload file: %s" % e)
log.info("Done uploading %s", full_path)
except paramiko.SSHException:
reconnect()
update_file(event)
except EOFError:
reconnect()
update_file(event)
except socket.timeout:
reconnect()
update_file(event)
except IOError, e:
if e.errno == errno.EACCES:
log.error("PERMISSION DENIED writing to %s", remote_path)
log.error("Dripbox was UNABLE TO SYNC %s to %s", full_path, remote_path)
else:
log.error("IOError: %s", str(e))
reconnect()
update_file(event)
def watch_files(paths):
global observer
observer = Observer()
stream = Stream(update_file, file_events=True, *paths)
observer.schedule(stream)
log.info("Starting observer")
observer.daemon = True
observer.start()
log.info("Observer started")