2

I am working on a code to copy images from a folder in a local directory to a remote directory. I am trying to use scp.

So in my directory, there is a folder that contains subfolders with images in it. There are also images that are in the main folder that are not in subfolders. I am trying to iterate through the subfolders and individual images and sort them by company, then make corresponding company folders for those images to be organized and copied onto the remote directory.

I am having problems creating the new company folder in the remote directory.

This is what I have:

def imageSync():
    path = os.path.normpath("Z:\Complete")
    folders = os.listdir(path)
    subfolder = []

    #separates subfolders from just images in complete folder
    for folder in folders:
        if folder[len(folder)-3:] == "jpg":   
            pass    
        else:
            subfolder.append(folder)

    p = dict()
    for x in range(len(subfolder)):
        p[x] = os.path.join(path, subfolder[x])

    sub = []
    for location in p.items():
        sub.append(location[1]) 

    noFold= []
    for s in sub:
        path1 = os.path.normpath(s)
        images = os.listdir(path1)
        for image in images:   
            name = image.split("-")
            comp = name[0]
            pathway = os.path.join(path1, image)
            path2 = "scp " + pathway + " blah@192.168.1.10: /var/files/ImageSync/" + comp
            pathhh = os.system(path2)
            if not os.path.exists(pathhh):
                noFold.append(image)

There's more to the code, but I figured the top part would help explain what I am trying to do.

I have created a ssh key in hopes of making os.system work, but Path2 is returning 1 when I would like it to be the path to the remote server. (I tried this: How to store the return value of os.system that it has printed to stdout in python?)

Also how do I properly check to see if the company folder in the remote directory already exists?

I have looked at Secure Copy File from remote server via scp and os module in Python and How to copy a file to a remote server in Python using SCP or SSH? but I guess I am doing something wrong.

I'm new to Python so thanks for any help!

Community
  • 1
  • 1
Alina DW
  • 111
  • 1
  • 17

1 Answers1

0

try this to copy dirs and nested subdirs from local to remote:

cmd = "sshpass -p {} scp -r {}/* root@{}://{}".format(
    remote_root_pass, 
    local_path, 
    remote_ip, 
    remote_path)
os.system(cmd)

don't forget to import os, You may check the exitcode returned (0 for success)

Also you might need to "yum install sshpass"

And change /etc/ssh/ssh_config StrictHostKeyChecking ask to: StrictHostKeyChecking no

Ohad the Lad
  • 1,889
  • 1
  • 15
  • 24