user2813956
user2813956

Reputation: 11

Connecting to a remote server using Python

I am trying to print the contents of a folder in a remote server. The code I have used is:

srcserver = 'abc.com'
dyndir = '\\\\%s\\E$\\Backup\\' %(srcserver)
ls = glob.glob('%s*' %dyndir)
print ls

When I try this, it returns an empty array. Could you please help me resolve this issue.

Upvotes: 1

Views: 6935

Answers (2)

Greg
Greg

Reputation: 5588

You should try using fabric

It provides a straight-forward ssh connection to your server and will allow you to run commands on a remote server, use sftp for file transfers, basically all the things you can do using ssh

Once you have fabric installed:

from fabric.api import run, settings

with settings(host_string="mybox-name"):
    run("ls /path/to/my/folder")

If you are using windows as the previous poster implies then I would suggest checking out this stackoverflow ticket

Upvotes: 1

Andrew Gorcester
Andrew Gorcester

Reputation: 19983

Accessing files in a remote server is actually really complicated! At some point, software has to establish a network connection, authenticate, translate filesystem commands into network packets and so forth. If you do it like this, using glob.glob like you would on a local filesystem, you're essentially relying on the Windows virtual filesystem to do all of this work for you. I'm not surprised that's not working, because there's a lot that can go wrong (for instance, the Windows vfs might be intercepting filesystem commands at a higher level than this relatively low-level way to access the filesystem).

If you definitely want to do it like this, then you should add the following information to your question:

  • Your exact operating system (this method will probably be fairly non-portable)
  • Whether the remote system in question has already been mounted by the user before the script is being run, or if you are trying to open a new connection
  • Whether you need to authenticate to the remote server in order to access it

There is probably additional relevant bits of information that I can't think of, because this starts to be more of a Windows question than a Python question when you look into it. You might want to add "Windows" and some other relevant keywords like "SMB" or "CIFS" to your question tags if you want to pursue a Windows vfs-based solution.

An alternative would be to use an SMB/CIFS client, taking the Windows filesystem out of the equation entirely. You could use Python to manipulate a command-line client, like smbclient. Or you could use a Python library to handle those bits, although it's not very common to use Python for this kind of thing so some libraries may be buggy, poorly supported or out-of-date. Google "Python SMB" if you want to try that approach; the first several hits are all relevant to this problem.

Upvotes: 0

Related Questions