【问题标题】:connecting to a remote server and downloading and extracting binary tar file using python连接到远程服务器并使用 python 下载和提取二进制 tar 文件
【发布时间】:2016-10-12 22:14:02
【问题描述】:

我想连接到远程服务器,下载二进制 tar 文件并将其解压缩到该主机上的特定目录中。我正在使用 python 2.6.8

  1. 通过 ssh 连接到该服务器的简单方法是什么?
  2. 我在我的脚本上看到以下错误以下载 tar 文件并解压缩它

    Traceback(最近一次调用最后一次): 文件“./wgetscript.py”,第 16 行,在 tar = tarfile.open(file_tmp) 文件“/usr/lib64/python2.6/tarfile.py”,第 1653 行,打开 返回函数(名称,“r”,fileobj,**kwargs) gzopen 中的文件“/usr/lib64/python2.6/tarfile.py”,第 1715 行 文件obj = bltn_open(名称,模式+“b”) TypeError: coercing to Unicode: need string or buffer, tuple found

#!/usr/bin/env python

import os
import tarfile
import urllib

url = 'http://**************/Lintel/Mongodb/mongodb-linux-x86_64-enterprise-suse12-3.2.6.tgz'

fullfilename = os.path.join('/tmp/demo1','file.tgz')
file_tmp = urllib.urlretrieve(url,fullfilename)
print file_tmp
base_name = os.path.basename(url)
print base_name
file_name, file_extension = os.path.splitext(base_name)
print file_name, file_extension
tar = tarfile.open(file_tmp)
nameoffile = os.path.join('/tmp/demo1','file')
tar.extractall(file_name,nameoffile)
tar.close()

【问题讨论】:

  • tarfile.open(fullfilename)
  • 我现在看到这个错误:文件“/usr/lib64/python2.6/tarfile.py”,第 2032 行,在 extractall if tarinfo.isdir(): AttributeError: 'str' object has no属性“isdir”

标签: python remote-server


【解决方案1】:

这里有2个错误:

  • urllib.urlretrieve(或 Python 3 中的 urllib.requests.urlretrieve)返回 tuple:文件名、httprequest。您必须将结果解压缩为 2 个值(或原始 fullfilename
  • 下载没问题,但tarfile 模块无法正常工作:tar.extractall 采用 2 个参数:.tar/.tgz 文件的路径和可选的成员 list(您可以在您的情况下使用tar.getmembers())。对于此示例,我建议我们删除该过滤器并提取 temp 目录中的所有内容。

固定代码:

url = 'http://**************/Lintel/Mongodb/mongodb-linux-x86_64-enterprise-suse12-3.2.6.tgz'
temp_dir = '/tmp/demo1'

fullfilename = os.path.join(temp_dir,'file.tgz')
# urllib.request in Python 3
file_tmp,http_message = urllib.urlretrieve(url,fullfilename)
base_name = os.path.basename(url)
file_name, file_extension = os.path.splitext(base_name)
tar = tarfile.open(file_tmp)

#print(tar.getmembers()[0:5])  # would print 5 first members of the archive

tar.extractall(os.path.join(temp_dir,file_name))
tar.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多