使用NOOP命令检查FTP连接是否有效

2024-06-18 11:08:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本在长时间的批量作业中似乎与FTP断开了连接。为了解决这个问题,我尝试制作一个如下所示的模块:

def connect_ftp(ftp):
    print "ftp1"
    starttime = time.time()
    retry = False
    try:
        ftp.voidcmd("NOOP")
        print "ftp2"
    except:
        retry = True
        print "ftp3"
    print "ftp4"
    while (retry):
        try:
            print "ftp5"
            ftp.connect()
            ftp.login('LOGIN', 'CENSORED')
            print "ftp6"
            retry = False
            print "ftp7"
        except IOError as e:
            print "ftp8"
            retry = True
            sys.stdout.write("\rTime disconnected - "+str(time.time()-starttime))
            sys.stdout.flush()
            print "ftp9"

我只使用以下命令调用函数:

^{pr2}$

但是,我跟踪了代码是如何使用print行运行的,并且在第一次使用模块时(甚至在连接到FTP之前)我的脚本运行ftp.voidcmd文件(“NOOP”)并且不排除它,因此最初不尝试连接到FTP。在

输出为:

ftp1
ftp2
ftp4
ftp success #this is ran after the module is called

我承认我的代码不是最好的,也不是最漂亮的,我还没有实现任何东西来确保如果我一直无法重新连接,我不会一直重新连接,但是我无法弄清楚为什么这对我的一生都不起作用,所以我看不到扩展模块的意义。这是连接/重新连接到FTP的最佳方法吗?在

提前谢谢你


Tags: 模块脚本falsetimeconnectftpprintretry
1条回答
网友
1楼 · 发布于 2024-06-18 11:08:10

这将连接到服务器:

ftp = ftplib.FTP('CENSORED')

因此,NOOP命令自然会成功,因为它不需要经过身份验证的连接。在

您的connect_ftp是正确的,只是您需要在connect调用中指定一个主机名。在

相关问题 更多 >