在自动化脚本中,文件下载是比较常见的操作,一般情况下,我们会将文件放到某个http服务器上,这时,当脚本中需要这个文件时,就需要使用到http下载的功能了
最基本的下载功能实现
实现最基本的功能,传入文件下载路径和文件本地保存路径,下载到本地
def DownloadFile(url,savePath):
"""
| [email protected]: 下载文件
| [email protected]:url:文件的url路径
| [email protected]:savePath:文件保存到的位置
| [email protected]:
"""
try:
url = url.strip()
savePath = savePath.strip()
InitPath(savePath)
r = urllib2.Request(url)
req = urllib2.urlopen(r)
saveFile = open(savePath, 'wb')
saveFile.write(req.read())
saveFile.close()
req.close()
except:
print traceback.format_exc()
代理下载功能实现
在有些情况下,比如,为了安全,某些机器不能直接访问服务器时,代理是一个比较好的解决方案,而脚本中涉及到文件下载时,就需要在文件下载过程中增加一些操作了
def DownloadFilebyProxy(url , savePath , host , port , user , pwd ):
try:
url = url.strip()
savePath = savePath.strip()
InitPath(savePath)
#如果代理需要验证
proxy_info = {'host' : host,
'port' : int(port),
'user' : user,
'pass' : pwd
}
proxy_support = urllib2.ProxyHandler({"http" : "http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
req = urllib2.urlopen(url)
saveFile = open(savePath, 'wb')
saveFile.write(req.read())
saveFile.close()
req.close()
except:
print traceback.format_exc()
上面对http下载功能做了简单的介绍,当然,有些情况下,我们需要通过脚本对ftp、ssh等服务器进行操作~·~
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/8333.html