Merging 2 slightly differnet shell scripts together to acheive same outcome


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Merging 2 slightly differnet shell scripts together to acheive same outcome
# 1  
Old 04-19-2015
Merging 2 slightly differnet shell scripts together to acheive same outcome

hi all.

i have a kimsufi server, and i am wanting to it to syncronise back to my home linux system, but i want it to track what files have been transfered, so that if i move or delete them on my system, they wont re-sync back.

i have googled around and found 2 scripts that acheive this, but they do it in a different way, and only 1 of them logs the files to a database.

this is the first script, it will log the files to a mysql database, and it wont re-sync them. but it does it over r-sync and i want more security than that. i also want it to split up the files and support parallel transfers. it also uses python.

Code:
#!/usr/bin/python

# DETAILS:
# This script is designed to push newly downloaded files from a seedbox (offshore, local on your network, or even local on the same machine) to a target machine or directory.
# It does this by polling the directory (locally) every 10 seconds for new downloads and once found will establish a rsync connection to push them to the target.
# Pushed files are logged in a SQLite database so they are not pushed again the next time the source directory is checked.
# The main advantage verses a plain old rsync script is the target directory can have files deleted from it while the source can continue seeding the files that were deleted on the target.
#
# INSTRUCTIONS:
# Run this script on your seedbox in the background using:
# ./seedbox-sync.py --verbose --progress --times /tmp/a/ /tmp/b/ &
# All parameters except the last two are optional and the trailing "&" will make bash run it in the background.
# The above example will sync files and directories from "/tmp/a/" to "/tmp/b/". If a file is later deleted from "/tmp/b/" it will never be resynced.
# The list of known files is kept in the seedbox-sync.sqlite file which is created at first run.
# IMPORTANT: Make sure the source directory is your torrent client's "completed" directory and not "incomplete" or regular download directory (see "moving files to another directory once complete") otherwise the sync will begin before the file has fully downloaded.
#
# EXAMPLE 1:
# ./seedbox-sync.py --progress /opt/deluge-complete/ john@home.dyndns.com:~/downloads/
# Running on a co-located seedbox, the Deluge client is set to copy completed files to /opt/deluge-complete/.
# After a download is complete the new file or directory will be copied to your home machine using SSH.
# All that is required here is on your home machine adding a user john, then creating a downloads directory for him in his home directory.
#
# EXAMPLE 2:
# ./seedbox-sync.py --verbose --progress --times /tmp/a/ /tmp/b/ &
# Sync all files from /tmp/a/ to /tmp/b/ where /tmp/a/ is the source where your torrent client saves completed files to and /tmp/b/ is the target where the downloads will be mirrored to.
# The above example is using this script as a local sync on the same machine which is still useful because you then can delete downloads from your mirrored target directory and still remain seeding on your torrent client.

import sqlite3
import os
import sys
import subprocess
from time import sleep

if len(sys.argv)<3:
 print("Please run with atleast two parameters.")
 exit(1)

sourceDir=sys.argv[-2].rstrip("/")
destDir=sys.argv[-1].rstrip("/")

# Create the database if it doesn't exist.
if not os.path.exists("seedbox-sync.sqlite"):
 print("No database found, creating new one...")
 con=sqlite3.connect("seedbox-sync.sqlite")
 con.execute("create table rememberedFiles(filename varchar);")
else:
 con=sqlite3.connect("seedbox-sync.sqlite")

def isFileRemembered(filename):
 cur=con.cursor()
 cur.execute("select count(*) from rememberedFiles where filename=?",(filename,))
 r=[row[0] for row in cur.fetchall()][0]
 cur.close()
 return r>0

def rememberFile(filename):
 con.execute("insert into rememberedFiles values(?)",(filename,))
 con.commit()

# The main loop.
while True:
 files=os.listdir(u""+sourceDir) # If you call os.listdir() with a UTF-8 string the result will be an array of UTF-8 strings instead of ASCII. Needed for passing UTF-8 into sqlite3 for filenames with special characters.
 
 print("Sleeping for 10 seconds...")
 sleep(10) # Sleep for 10 seconds between scans.
 
 for file in files:
  if(isFileRemembered(file)):
   # This file has been copied already.
   print("Skipping file: "+file)
   continue

  # Sync the file.
  print("Syncing new file: "+file)
  cmd=["rsync"]
  #cmd.append("--rsh=ssh -p22222") # Uncomment this line if your target directory or machine is listening on a port other than 22.
  if "--verbose" in sys.argv:
   cmd.append("--verbose")
  if "--progress" in sys.argv:
   cmd.append("--progress")
   
  # Give files in destination 0777 permissions for some NAS setups, but optional.
  cmd.append("--chmod=ugo+rwx")
  cmd.append("--perms")
  
  cmd.append("--delay-updates")
  cmd.append("--recursive")
  cmd.append(sourceDir+"/"+file)
  cmd.append(destDir+"/")
  p=subprocess.Popen(cmd,shell=False)
  if p.wait()==0:
   rememberFile(file)
   print("Synced & remembered: "+file)
  else:
   print("Failed to sync: "+file)

con.close()


this is the second script that uses bash, and sends the files over LFTP. it therefor supports ssh and SFTP.

Code:
#!/bin/bash
login="username"
pass="password"
host="server.feralhosting.com"
remote_dir='~/folder/you/want/to/copy'
local_dir="$HOME/lftp/"

base_name="$(basename "$0")"
lock_file="/tmp/$base_name.lock"
trap "rm -f $lock_file" SIGINT SIGTERM
if [ -e "$lock_file" ]
then
    echo "$base_name is running already."
    exit
else
    touch "$lock_file"
    lftp -p 22 -u "$login","$pass" sftp://"$host" << EOF
    set sftp:auto-confirm yes
    set mirror:use-pget-n 5
    mirror -c -P5 --log="/var/log/$base_name.log" "$remote_dir" "$local_dir"
    quit
EOF
    rm -f "$lock_file"
    trap - SIGINT SIGTERM
    exit
fi

so i want to merge them together and have it use LFTP for the transfer, and then log it all to a mysql database.

but my coding ability is very limited. and i have no idea on how to do it. would anyone here be able to point me in the right direction to achieve the results im after?

cheers

Jason
# 2  
Old 04-19-2015
Hello Jason and welcome to the Forums.

Firstly let me start by trying to alleviate your concerns about rsync. Rsync uses ssh to perform it's transfers so it's every bit as secure as sftp via lftp.

Although python is a little more challenging to write and support than shell I think you have a program that is doing what you need and re-writing it in shell is probably unnecessary. Also because shell interaction with mysql databases is a little inelegant, this type of feature (processed list) is usually handled with a flat text file and unix tools like grep/awk.
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Programming

A Slightly Better NTP Client for the ESP8266

Was not really happy with the NTP clients for the ESP8266 because, after a few years of game engine programming, I am not a fan of a lot of code and delays in the main loop, so here is a "slightly better NTP client" for the ESP8266. In a nutshell, instead of having a delay in the main loop as a... (1 Reply)
Discussion started by: Neo
1 Replies

2. Shell Programming and Scripting

Considered basic but advanced outcome (Custom Backup Solution)

Ive a problem that I'm reaching out for help. Ive written (With bits and pieces) of script that is not running as expected or is having an issue causing processes to spiral out of control. The script does this: Unloads a UV database server Tars up a few folders Transfers the file to... (11 Replies)
Discussion started by: coastdweller
11 Replies

3. Shell Programming and Scripting

Merging together two awk scripts

I have two awk scripts shown below. checkTrvt.awk works on file format .xt, whereas checkData.awk workds on file format .dat I want to merge the two scripts together, if I find that the user passed .xt file I do the code for .xt file, whereas if user passes .dat file, I go through the code for... (9 Replies)
Discussion started by: kristinu
9 Replies

4. Shell Programming and Scripting

use ind command to search files on differnet server

Hi, I am writing script to search the directories on different server. I have 3 servers. eg. ser1, ser2, ser2 find <absolute_path>-type d -user <user_name> -ctime +5 -exec ls -ltd {} \; can someone please suggest me some way how can i use find command for this. i have ssh connectivity... (1 Reply)
Discussion started by: vikash_k
1 Replies

5. Solaris

How to analyze the outcome of patchdiag

Hi Gurus, I have installed the stuff needed for patchdiag for patching, its working okay , however after execution of pathcdiag.sparc i am unable to understand the summury which is produced at the end. Please help ! Thanks (3 Replies)
Discussion started by: kumarmani
3 Replies

6. Shell Programming and Scripting

merging of 2 files AWK, SHELL or something else

I have 2 files pipe delimted and want to merge them based on a key e.g file 1 123|xxx|yyy|zzz 345|xab|yzy|zyz 456|sss|ttt|foo file 2 123|hhh|ggg|xxx 345|ddd|www|ddd|fff 456|ddd|sss|sss|eee so if the key is the first field, and the result should be file 1 with field 2 from file 2... (24 Replies)
Discussion started by: klut
24 Replies

7. Shell Programming and Scripting

Mail to: cc: How can i acheive this with ksh

Hi All, I have to write a script to send mail, in that i have to dynamically add the recepient in TO and my cc is a common one. For all mails my cc recepients are same. Only problem with TO recepient. Please i am looking for your inputs. (1 Reply)
Discussion started by: Arunprasad
1 Replies

8. Shell Programming and Scripting

How to acheive ALT+Enter of xls in Unix ksh/sqlplus

Hi, I am using sqlplus (called inside my ksh) to create a file which is mailed to the users as an xls. There is one DESCRIPTION column which is currently coming as wrapped, but, the users want a new line for each of the fields present in the desricription column. Below is an example - ... (11 Replies)
Discussion started by: Sree_2503
11 Replies

9. UNIX for Dummies Questions & Answers

Backup Differnet Unix OS Using Single LTO

Hi Gurus, I would like to clarify some doubts regarding a backup strategy. I have been working on various *NIX as AIX,Solaris and Linux. I would like to design a backup procedure.WOuld it be possible for me to use a single LTO tape device to backup all the different server with different... (2 Replies)
Discussion started by: mickykt
2 Replies
Login or Register to Ask a Question