Avión
Avión

Reputation: 8376

Accessing a windows shared folder from Linux using Python

I've a shared folder created (with access to everyone) in Windows. on C:\sharedfolder, so I can access it with:

\\mylocalnetworkip\sharedfolder

Now I want a Python script to write stuff there from another machine.

If I run this simple script on Windows (from my machine, using Python under Windows), it works. It creates the file and writes that content.

file = open(r'\\mylocalnetworkip\sharedfolder\tester.dat', 'w')
file.write('whatever')
file.close()

But if I run the same script in Linux (from another machine, but still on my local network, this means if I ping my IP it works), it doesn't work.

With it doesn't work I mean that it doesn't fail, the strange thing that it creates a file on the same path with the name of the entire

root@mc:/tmp# python tester.py  <-- the script with the code above
root@mc:/tmp# ls
\\mylocalnetworkip\sharedfolder\tester.dat  tester.py
root@mc:/tmp# cat \\mylocalnetworkip\sharedfolder\tester.dat
whatever
root@mc:/tmp#

Can someone give me a hand and tell me how can I make it work in Linux? Thank you!

PS: I also tested it using '\\\\mylocalnetworkip\\sharedfolder\\tester.dat' with no luck.

Upvotes: 3

Views: 16238

Answers (1)

buhtz
buhtz

Reputation: 12152

Two problems here.

Mounting

Linux is not able to handle paths like this \\mylocalnetworkip\sharedfolder\tester.dat.

On a Linux system you first have to "mount" a shared folder before you can use it. After mountig (depending on the mount point) the path could look like this /mnt/mylocalnetworkip/sharedfolder/tester.dat.

There are different ways to mount on Linux. e.g. check out https://unix.stackexchange.com/q/18925/136851 or https://www.putorius.net/mount-windows-share-linux.html

Path separators

Windows and Linux using different path separators. A fine solution in Python is to create a path like this.

import os
os.path.join('/', 'mnt', 'mylocalnetworkip', 'sharedfolder', 'tester.dat')

The result is

/mnt/mylocalnetworkip/sharedfolder/tester.dat

Be aware of the first / which indicates the root of the linux filesystem.

Upvotes: 3

Related Questions