4、对于ftp浏览的模拟,我没有直接使用python的ftp模块,而是通过python模拟命令行输入来直接控制linux客户的ftp操作,所以在使用本脚本之前,linux之中必须先安装ftp客户端,并支持命令行操作。首先一个标准的ftp流程应该是这样的:
我们发现这种ftp的shell操作是有交互的,所以简单的os.popen()肯定是不行了,所以我选择使用pexpect库这个库的主要作用就是输入shell指令,然后看出来的指令是否符合预期的指令,然后在输入下一步指令,从而完成交互操作,对ftp的长传操作的代码如下
def ftp_download(url,username,pwd,filename): #ftp的上传文件 command='ftp '+url child=pexpect.spawn(command) print child.readline() index=child.expect(["(?i)Name","(?i)Unknown host",pexpect.EOF,pexpect.TIMEOUT]) #pexpect函数的主要作用就是交互shell命令 if(index==0): #原理就是判断下一步的shell提示是否包含指定的字符串 child.sendline(username) print 'Name'+child.readline() index=child.expect(["(?i)Password",pexpect.EOF,pexpect.TIMEOUT]) if(index==0): child.sendline(pwd) print 'Password'+child.readline() index=child.expect(['ftp>','Login incorrect']) if(index==0): child.sendline('get '+filename) index=child.expect('secs') if(index==0): print child.before+'secs' child.close() else: print 'ftp false' child.close()可以看到主要的流程就是先通过pexpect.spawn()函数输入初始命令,然后判断输入指令之后可能的结果index=child.expect([“(?i)Name”,”(?i)Unknown host”,pexpect.EOF,pexpect.TIMEOUT]) 这里我设置了结果预期结果,如正常的让你输入name、未知的主机unknown host 、timeout、流结束等,然后做出判断,如果预期结果为name就进行输入用户名的操作。可以通过child.before、child.readline()等函数来获取shell中的信息,判断程序是否正常进行