Mine is similar to this question.
How to copy a file from a network share to local disk with variables?
The only difference is my network drive has a password protect with username and password.
I need to copy files to a Samba
share using Python
and verify it.
If I manually login in then the code works, but without logging in the shutil
command does not work.
I'd try mapping the share to an unused drive letter by calling the
NET USE
command usingos.system
(assuming you are on Windows):After you mapped the share to a drive letter, you can use
shutil.copyfile
to copy the file to the given drive. Finally, you should unmount the share:Of course this works only on Windows, and you will have to make sure that the drive letter P is available. You can check the return code of the
NET USE
command to see whether the mount succeeded; if not, you can try a different drive letter until you succeed.Since the two
NET USE
commands come in pair and the second one should always be executed when the first one was executed (even if an exception was raised somewhere in between), you might wrap these two calls in a context manager if you are using Python 2.5 or later:If you have the pywin32 library (eg comes part of the ActiveState Python distro), then you can get it done in a few lines, without mapping a drive:
There is a more complete example on ActiveState Code