PK S-5Έ? bΘ Θ zc/__init__.py# this is a namespace package
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
PK ωvo6έεpSg g zc/__init__.pyc;ς
₯Ec @ sO y d k Z e i e Wn. e j
o" d k Z e i e e Z n Xd S( N( s
pkg_resourcess declare_namespaces __name__s ImportErrors pkgutils extend_paths __path__( s __path__s
pkg_resourcess pkgutil( ( s) build/bdist.linux-i686/egg/zc/__init__.pys ? s
PK jvo6Ξo₯ ₯ zc/buildoutsftp/urllib2sftp.py##############################################################################
#
# Copyright (c) 2005 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""SFTP Handler for urllib2
$Id: urllib2sftp.py 73201 2007-03-15 18:51:12Z jim $
"""
import cStringIO, getpass, mimetypes, os, re, stat, sys, urllib, urllib2
import paramiko
parse_url_host = re.compile(
'(?:' '([^@:]+)(?::([^@]*))?@' ')?'
'([^:]*)(?::(\d+))?$').match
if sys.platform == 'win32':
import _winreg
parse_reg_key_name = re.compile('(rsa|dss)2?@22:(\S+)$').match
def _get_hosts_keys():
regkey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
r'Software\SimonTatham\PuTTY\SshHostKeys',
)
keys = paramiko.HostKeys()
i = 0
while 1:
try:
name, value, type_ = _winreg.EnumValue(regkey, i)
i += 1
value = [long(v, 16) for v in value.split(',')]
ktype, host = parse_reg_key_name(name).groups()
if ktype == 'rsa':
key = paramiko.RSAKey(vals=value)
if ktype == 'dss':
key = paramiko.DSSKey(vals=value)
keys.add(host, 'ssh-'+ktype, key)
except WindowsError:
break
return keys
else:
def _get_hosts_keys():
return paramiko.HostKeys(os.path.expanduser('~/.ssh/known_hosts'))
class Result:
def __init__(self, fp, url, info):
self._fp = fp
self.url = url
self.headers = info
def geturl(self):
return self.url
def info(self):
return self.headers
def __getattr__(self, name):
return getattr(self._fp, name)
class SFTPHandler(urllib2.BaseHandler):
def sftp_open(self, req):
host = req.get_host()
if not host:
raise IOError, ('sftp error', 'no host given')
parsed = parse_url_host(host)
if not parsed:
raise IOError, ('sftp error', 'invalid host', host)
user, pw, host, port = parsed.groups()
if user:
user = urllib.unquote(user)
else:
user = getpass.getuser()
if port:
port = int(port)
else:
port = 22
if pw:
pw = urllib.unquote(pw)
host = urllib.unquote(host or '')
hostkey = _get_hosts_keys()
hostkey = hostkey.get(host)
if hostkey is None:
raise paramiko.AuthenticationException(
"No stored host key", host)
[hostkeytype] = list(hostkey)
hostkey = hostkey[hostkeytype]
if pw is not None:
trans = paramiko.Transport((host, port))
trans.connect(username=user, password=pw)
else:
for key in paramiko.Agent().get_keys():
trans = paramiko.Transport((host, port))
try:
trans.connect(username=user, pkey=key, hostkey=hostkey)
break
except paramiko.AuthenticationException:
trans.close()
else:
raise paramiko.AuthenticationException(
"Authentication failed.")
sftp = paramiko.SFTPClient.from_transport(trans)
path = req.get_selector()
url = req.get_full_url()
mode = sftp.stat(path).st_mode
if stat.S_ISDIR(mode):
return Result(
cStringIO.StringIO('\n'.join([
('%s
'
% (url, x, x)
)
for x in sftp.listdir(path)
])),
url, {'content-type': 'text/html'})
else:
mtype = mimetypes.guess_type(url)[0]
if mtype is None:
mtype = 'application/octet-stream'
return Result(sftp.open(path), url, {'content-type': mtype})
PK S-5₯ zc/buildoutsftp/__init__.py#
PK Γ-5 $₯g g zc/buildoutsftp/tests.py##############################################################################
#
# Copyright (c) 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
import os, stat, StringIO, sys, urllib2, getpass
import paramiko
from zope.testing import doctest
class Replace:
def __init__(self, module, **attrs):
self.module = module
self.original = original = {}
for name, value in attrs.iteritems():
original[name] = getattr(module, name)
setattr(module, name, value)
def restore(self):
for name, value in self.attrs.iteritems():
setattt(self.module, name, value)
class User:
def __init__(self, name, key=None, pw=None, nameonly=False):
self.name = name
self.key = paramiko.PKey(key)
self.pw = pw
self.nameonly = nameonly
def auth(self, key, pw):
return (
(key is not None and key == self.key)
or
(pw is not None and pw == self.pw)
or
self.nameonly
)
hkeys = [
('foo.com', ),
('foo.org', 'foo.orgkey'),
('foo.net', 'foo.netkey'),
('foo.biz', 'foo.bizkey'),
]
hostdata = {
'foo.com': (
dict(
docs = dict(
greet = 'Hello\nWorld!\n'
)
),
'foo.comkey',
[User('testuser', 'UserKey1')],
),
}
class FauxTransport:
def __init__(self, addr):
self.host, self.port = addr
if self.host in hostdata:
self.fs, self.hkey, users = hostdata[self.host]
self.users = dict([(u.name, u) for u in users])
else:
self.fs, self.hkey, self.users = {}, None, {}
def connect(self, hostkey=None, username='', password=None, pkey=None):
user = self.users.get(username)
if user is None or not user.auth(pkey, password):
raise paramiko.AuthenticationException('Authentication failed.')
if hostkey != self.hkey:
raise paramiko.SSHException("Bad host key from server")
class FauxAgent:
def get_keys(self):
return [paramiko.PKey('UserKey1'), paramiko.PKey('UserKey2')]
class FauxStat:
def __init__(self, mode):
self.st
class FauxSFTPClient:
def __init__(self, transport):
self.transport = transport
def _traverse(self, path):
path = path.split('/')[1:]
f = self.transport.fs
for p in path:
if isinstance(f, str) or p not in f:
raise IOError('[Errno 2] No such file')
f = f[p]
return f
def sftp_stat(self, path):
f = self._traverse(path)
if isinstance(d, dict):
return FauxStat(stat.S_IFDIR)
else:
return FauxStat(0)
def open(self, path):
return StringIO.StringIO(self._traverse(path))
def setup(test):
# We're going to replace much of paramiko, and, if necessary, _winreg
# to try to control urllib2sftp's environment.
teardown = []
test.globs['__teardown'] = teardown
oldhome = os.environ.get('HOME')
if oldhome is None:
teardown.append(lambda:os.environ.__delitem__('HOME'))
else:
teardown.append(lambda:os.environ.__setitem__('HOME', oldhome))
os.environ['HOME'] = '/testhome'
# :( urllib2 needs to grow an api to get the opener so it can be
# restored by tests
old_opener = urllib2._opener
teardown.append(lambda: urllib2.install_opener(old_opener))
if sys.platform == 'win32':
import _winreg
key = object()
def OpenKey(*args):
if args != (_winreg.HKEY_CURENT_USER,
r'Software\SimonTatham\PuTTY\SshHoskKeys'):
raise ValueError("Bad keys", *args)
return key
def EnumValue(k, index):
if k is not key:
raise ValueError('Bad key')
try:
host, hkey = hkeys[index]
except IndexError:
raise WindowsError(index)
return 'rsa@22:'+host, hkey, 0
HostKeys = paramiko.HostKeys
teardown.append(Replace(_winreg,
OpenKey=OpenKey,
EnumValue=EnumValue,
).restore
)
else:
def HostKeys(path=None):
if path != '/testhome/.ssh/known_hosts':
raise IOError('No such file', path)
return dict([
(host, {'ssh-rsa': paramiko.PKey(hkey)})
for (host, hkey) in hkeys
])
teardown.append(Replace(getpass, getuser=lambda: 'testuser').restore)
teardown.append(Replace(
paramiko,
Transport = FauxTransport,
Agent = FauxAgent,
SFTPClient = FauxSFTPClient,
HostKeys = HostKeys,
))
def teardown(test):
for f in test.globs['__teardown']:
f()
def test():
"""
Install the urllib2 hook
>>> import zc.buildoutsftp.buildoutsftp
>>> zc.buildoutsftp.buildoutsftp.install(None)
Now, we'll try to get a directory listing from foo.com:
>>> f = urllib2.urlopen('sftp://foo.com')
>>> f.url
'sftp://foo.com'
>>> f.info['Content-Type']
'text/html'
>>> print f.read()
"""
def test_suite():
return doctest.DocTestSuite(setUp=setup, tearDown=teardown)
PK -\-5/kΝΑ9 9 zc/buildoutsftp/buildoutsftp.py##############################################################################
#
# Copyright (c) 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
import urllib2
import zc.buildoutsftp.urllib2sftp
def install(buildout=None):
urllib2.install_opener(
urllib2.build_opener(zc.buildoutsftp.urllib2sftp.SFTPHandler)
)
PK ωvo61ΰιΏ Ώ zc/buildoutsftp/urllib2sftp.pyc;ς
¨ωEc @ sγ d Z d k Z d k Z d k Z d k Z d k Z d k Z d k Z d k Z d k Z d k
Z
e i d i Z
e i d j o( d k Z e i d i Z d Z n
d Z d f d YZ d e i f d
YZ d S( sO SFTP Handler for urllib2
$Id: urllib2sftp.py 73201 2007-03-15 18:51:12Z jim $
Ns. (?:([^@:]+)(?::([^@]*))?@)?([^:]*)(?::(\d+))?$s win32s (rsa|dss)2?@22:(\S+)$c C s, t i t i d }
t i } d } xϊ n oς yΧ t i |
| \ } } } | d 7} g i } | i d D] } | t | d qp ~ } t | i \ } } | d j o t i d | } n | d j o t i d | } n | i | d | | Wq* t j
o Pq* Xq1 W| Sd S(
Ns&