pythonlinuxwindowscifs

Python copy files from Linux to WIndows


I'm building a website which has a form which captures user data and runs some cgi on the user data. One of the first steps of the cgi is that it needs to copy files from the linux webserver to windows machines. The server would be using an active directory role acount for the copy credential. I had hoped to simply use something like this:

mount -t cifs -o username=someUsername,password=somePasword //someMachine/someShare /someMountPoint

Unfortunately I get errors about the password attributed being invalid when I run that command in bash. Ideally I would use this method to mount the remote windows c$ share and then copy the files but I'm willing to try other modules if they make more sense.

I had something like this but it doesn't work, creates the necessary temporary directories but never mounts anything. I'm happy to try using something else but would love to know what's wrong here.

import subprocess
import random


def makeDir():
    tempDir = random.randrange(111111,999999)
    subprocess.Popen(["mkdir","/mntDir/"+str(tempDir)])
    return tempDir

def mountShare(hostname, username, password):
    mountDir = makeDir()
    try:
        subprocess.Popen(["mount","-t","cifs", "-o",
                      "username="+username+",password="+password,
                      "//"+hostname+"/c$",
                      "/mntDir/"+mountDir])
    except:
        print("Mounting failed")


Solution

  • I used the SMBConnection class found in pysmb (https://pythonhosted.org/pysmb/api/smb_SMBConnection.html). Very simple and no need for mounting.

     conn = SMBConnection(user, pw, myname, srv, use_ntlm_v2 = True)
     conn.connect(ip, port=139)
     file2transfer = open(filename,"r")
     conn.storeFile(share,path + filename, file2transfer, timeout=30 )
    

    Make sure that the user has logon rights to the fileshare.