1

I am working with a FTP Server where i would like to try to connect at it constantly when i have no response of it like internet failed or something. I proved under normal conditions and i am able to connect succesfully but what i want now is to loop the connection with a certain time since after some seconds of trying to connect the Jupyter notebook gives me an error and stops the program.

The objective is to be able to constantly try to connect to the ftp server until it does and then jump to the next statement While a==1: so since i had that jupyter notebook problem what i tryed is to put an if where after 5 seconds it breaks the loop.

Does someone have any other solution to this it still doesn't work.Thx for reading :)

while a==0:
    print('starting 1rst loop')

    while True:
        timeout = time.time() + 5   # 5 seconds from now
        while a==0 :
            print("Connecting to FTP Server")
            #domain name or server ip:
            ftp = FTP('ftpIP')
            #Passw and User
            ftp.login(user=XXX, passwd = XXX)
            print('Connected to the FTP server')
            ftp.quit()
            ftp.close()
            a= a+1
            if  a==0 and time.time() > timeout:
                timeout=0
                break
while a==1:
MarcoPolo11
  • 81
  • 1
  • 1
  • 11

1 Answers1

1

Although I do not quite understand what you mean, how does this look?

import time
import socket
from ftplib import FTP


def try_connect(host, user, passwd):
    print('Connecting to FTP Server')
    ftp = FTP()
    try:
        # domain name or server ip
        ftp.connect(host, timeout=5)
    except socket.error:
        print('Connect failed!')
        return False
    # Passwd and User
    ftp.login(user, passwd)
    print('Connected to the FTP server')
    ftp.quit()
    ftp.close()
    return True


def main():
    while True:
        try_connect('192.168.1.1', user='anonymous', passwd='')
        print()
        time.sleep(5)


if __name__ == '__main__':
    main()

It tries to connect FTP every 5 seconds and output the result.

DDGG
  • 1,171
  • 8
  • 22
  • If you want to exit the loop when it's connected successfully, you can use the return value of the `try_connect` function. – DDGG Feb 22 '18 at 18:10
  • Cool i think its what i need! Do you mind telling me what the last line does with the __name__ what i understand is that u call main() (@DDGG) if __name__ == '__main__': main() – MarcoPolo11 Feb 23 '18 at 08:29
  • It's Python's idioms, you can learn more from [here](https://stackoverflow.com/a/22493194/1730599) and [here](https://stackoverflow.com/a/419185/1730599). Good luck! @MarcoPolo11 – DDGG Feb 23 '18 at 09:01