Skip to content

Instantly share code, notes, and snippets.

@Mytherin
Last active August 12, 2016 11:12
Show Gist options
  • Save Mytherin/f8163702c7e3e0b8a67f11c0949622eb to your computer and use it in GitHub Desktop.
Save Mytherin/f8163702c7e3e0b8a67f11c0949622eb to your computer and use it in GitHub Desktop.
Automatically scp over files in a directory to the target machine whenever they are changed on the host machine.
#!/usr/bin/python
import os, time, sys, datetime
if len(sys.argv) < 3 or ':' not in sys.argv[2]:
print("Usage: scpsync [sourcepath] [dest:destpath] [src?]")
exit(1)
srcheaders = ['.h', '.c', '.py', '.r', '.hpp', '.cpp', '.mal', '.sql', '.malC','.php', '.html']
source = sys.argv[1]
dest = sys.argv[2]
srconly = False
if len(sys.argv) >= 4 and sys.argv[3] == 'src':
srconly = True
source = source.replace('~', os.environ['HOME'])
if source[0] != '/':
source = os.path.join(os.getcwd(), source)
destmachine = dest.split(':')[0]
destfolder = dest.split(':')[1]
def get_modified_files(dir):
global modified_times, srconly, srcheaders
files = os.listdir(dir)
for f in files:
fpath = os.path.join(dir, f)
if os.path.isfile(fpath):
include = True
if srconly:
include = False
for header in srcheaders:
if fpath.endswith(header):
include = True
if include:
modified = datetime.datetime.fromtimestamp(os.path.getmtime(fpath))
modified_times[fpath] = [modified]
elif os.path.isdir(dir):
get_modified_files(fpath)
if os.path.isfile(source):
print("Beginning sync of file '%s'" % source)
now = datetime.datetime.fromtimestamp(os.path.getmtime(source))
while True:
modified = datetime.datetime.fromtimestamp(os.path.getmtime(source))
if modified > now:
print("Syncing file %s (%s)" % (source, str(modified)))
os.system('scp %s %s:%s' % (source, destmachine, destfolder))
now = modified
time.sleep(1)
exit(1)
elif os.path.isdir(source):
if source[-1] != '/':
source = source + '/'
modified_times = {}
get_modified_files(source)
print("Beginning sync of folder '%s' (%d items)" % (source, len(modified_times)))
while True:
for fpath,prevmodified in modified_times.iteritems():
modified = datetime.datetime.fromtimestamp(os.path.getmtime(fpath))
if modified > prevmodified[0]:
print("Syncing file %s (%s)" % (fpath, str(modified)))
os.system('scp %s %s:%s' % (fpath, destmachine, os.path.join(destfolder, fpath.replace(source, ''))))
prevmodified[0] = modified
time.sleep(1)
exit(1)
else:
print("Could not find file or folder '%s'" % source)
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment