Search code examples
pythonpython-2.7ftpwmiftplib

Python script to download file from FTP site


I have a laptop which has a static IP (193.2.1.8)and is part of a small local private network without internet access. Quite often, I am required to do the following:

  1. Disconnect the lan cable of the private network from Laptop.
  2. Connect the laptop to the lan cable that has internet access.
  3. Change the IP configuration from static IP to detect automatically in the windows network configuration.
  4. Open FileZilla(a FTP program) and connect it to the FTP site, select a file(a known file name) and download to a specfic location on the harddisk.
  5. Then disconnect the lan cable that has internet access.
  6. Connect back the lan cable of private network.
  7. Change the IP configuration back to original static IP and subnet mask.

I would like to simply this process. Thus thinking of creating a Python Script that will

  1. Change the IP configuration of windows automatically.
  2. Connect to FTP site and download the file to a location.
  3. Change the IP configuration back to original setting.

Thanks to a post on SO which suggested to use WMI module, I managed to change the IP configuration using WMI module like this:

import wmi
nic_configs=wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)
nic = nic_configs[0]
nic.EnableDHCP()

But my question now is, how do I know if I am safe to proceed with my FTP operation? How do I know that if the internet connection is live after I have enabled the DHCP?

For the FTP operation, I am thinking of using ftplib.

Is there any better approach to this?

FYI: I am on windows XP SP3 32bits, python 2.7.5


Solution

  • how do I know if I am safe to proceed with my FTP operation?

    The first step in using ftplib is to create an FTP instance. If you give it a host name, the method call connect(host) is made for you. If the network is unreachable, it will fail in it's connection attempt and an exception is raised. There is also a timeout option to set connection timeout.

    If the connection attempt is successful, your network adapter was obviously ready. If an exception was raised, it was not. You can build your logic for connecting based on that (ideally using a retry decorator, or even a simple loop with a small sleep between each attempt).