Fix dict iters, sorts, exceptions, bytes renames and tuple args

This commit is contained in:
Scott Maxwell 2013-10-30 16:46:33 -07:00
parent 6bd1e42b43
commit 2ea352b8ba
24 changed files with 160 additions and 125 deletions

View File

@ -90,7 +90,7 @@ from paramiko.config import SSHConfig
from paramiko.proxy import ProxyCommand from paramiko.proxy import ProxyCommand
# fix module names for epydoc # fix module names for epydoc
for c in locals().values(): for c in list(locals().values()):
if issubclass(type(c), type) or type(c).__name__ == 'classobj': if issubclass(type(c), type) or type(c).__name__ == 'classobj':
# classobj for exceptions :/ # classobj for exceptions :/
c.__module__ = __name__ c.__module__ = __name__

View File

@ -308,7 +308,8 @@ class AuthHandler (object):
keyblob = m.get_string() keyblob = m.get_string()
try: try:
key = self.transport._key_info[keytype](Message(keyblob)) key = self.transport._key_info[keytype](Message(keyblob))
except SSHException, e: except SSHException:
e = sys.exc_info()[1]
self.transport._log(INFO, 'Auth rejected: public key: %s' % str(e)) self.transport._log(INFO, 'Auth rejected: public key: %s' % str(e))
key = None key = None
except: except:

View File

@ -615,7 +615,7 @@ class Channel (object):
""" """
try: try:
out = self.in_buffer.read(nbytes, self.timeout) out = self.in_buffer.read(nbytes, self.timeout)
except PipeTimeout, e: except PipeTimeout:
raise socket.timeout() raise socket.timeout()
ack = self._check_add_window(len(out)) ack = self._check_add_window(len(out))
@ -665,7 +665,7 @@ class Channel (object):
""" """
try: try:
out = self.in_stderr_buffer.read(nbytes, self.timeout) out = self.in_stderr_buffer.read(nbytes, self.timeout)
except PipeTimeout, e: except PipeTimeout:
raise socket.timeout() raise socket.timeout()
ack = self._check_add_window(len(out)) ack = self._check_add_window(len(out))

View File

@ -193,8 +193,8 @@ class SSHClient (object):
self.load_host_keys(self.known_hosts) self.load_host_keys(self.known_hosts)
f = open(filename, 'w') f = open(filename, 'w')
for hostname, keys in self._host_keys.iteritems(): for hostname, keys in self._host_keys.items():
for keytype, key in keys.iteritems(): for keytype, key in keys.items():
f.write('%s %s %s\n' % (hostname, keytype, key.get_base64())) f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
f.close() f.close()
@ -452,8 +452,8 @@ class SSHClient (object):
two_factor = (allowed_types == ['password']) two_factor = (allowed_types == ['password'])
if not two_factor: if not two_factor:
return return
except SSHException, e: except SSHException:
saved_exception = e saved_exception = sys.exc_info()[1]
if not two_factor: if not two_factor:
for key_filename in key_filenames: for key_filename in key_filenames:
@ -466,8 +466,8 @@ class SSHClient (object):
if not two_factor: if not two_factor:
return return
break break
except SSHException, e: except SSHException:
saved_exception = e saved_exception = sys.exc_info()[1]
if not two_factor and allow_agent: if not two_factor and allow_agent:
if self._agent == None: if self._agent == None:
@ -482,8 +482,8 @@ class SSHClient (object):
if not two_factor: if not two_factor:
return return
break break
except SSHException, e: except SSHException:
saved_exception = e saved_exception = sys.exc_info()[1]
if not two_factor: if not two_factor:
keyfiles = [] keyfiles = []
@ -514,17 +514,15 @@ class SSHClient (object):
if not two_factor: if not two_factor:
return return
break break
except SSHException, e: except (SSHException, IOError):
saved_exception = e saved_exception = sys.exc_info()[1]
except IOError, e:
saved_exception = e
if password is not None: if password is not None:
try: try:
self._transport.auth_password(username, password) self._transport.auth_password(username, password)
return return
except SSHException, e: except SSHException:
saved_exception = e saved_exception = sys.exc_info()[1]
elif two_factor: elif two_factor:
raise SSHException('Two-factor authentication requires a password') raise SSHException('Two-factor authentication requires a password')

View File

@ -173,7 +173,7 @@ class SSHConfig (object):
ret = {} ret = {}
for match in matches: for match in matches:
for key, value in match['config'].iteritems(): for key, value in match['config'].items():
if key not in ret: if key not in ret:
# Create a copy of the original value, # Create a copy of the original value,
# else it will reference the original list # else it will reference the original list

View File

@ -184,8 +184,8 @@ class DSSKey (PKey):
# DSAPrivateKey = { version = 0, p, q, g, y, x } # DSAPrivateKey = { version = 0, p, q, g, y, x }
try: try:
keylist = BER(data).decode() keylist = BER(data).decode()
except BERException, x: except BERException:
raise SSHException('Unable to parse key file: ' + str(x)) raise SSHException('Unable to parse key file: ' + str(sys.exc_info()[1]))
if (type(keylist) is not list) or (len(keylist) < 6) or (keylist[0] != 0): if (type(keylist) is not list) or (len(keylist) < 6) or (keylist[0] != 0):
raise SSHException('not a valid DSA private key file (bad ber encoding)') raise SSHException('not a valid DSA private key file (bad ber encoding)')
self.p = keylist[1] self.p = keylist[1]

View File

@ -254,14 +254,14 @@ class BufferedFile (object):
@rtype: list @rtype: list
""" """
lines = [] lines = []
bytes = 0 byte_count = 0
while True: while True:
line = self.readline() line = self.readline()
if len(line) == 0: if len(line) == 0:
break break
lines.append(line) lines.append(line)
bytes += len(line) byte_count += len(line)
if (sizehint is not None) and (bytes >= sizehint): if (sizehint is not None) and (byte_count >= sizehint):
break break
return lines return lines

View File

@ -91,8 +91,8 @@ class HostKeyEntry:
log.info("Unable to handle key of type %s" % (keytype,)) log.info("Unable to handle key of type %s" % (keytype,))
return None return None
except binascii.Error, e: except binascii.Error:
raise InvalidHostKey(line, e) raise InvalidHostKey(line, sys.exc_info()[1])
return cls(names, key) return cls(names, key)
from_line = classmethod(from_line) from_line = classmethod(from_line)

View File

@ -95,14 +95,14 @@ class KexGex (object):
q = (self.p - 1) // 2 q = (self.p - 1) // 2
qnorm = util.deflate_long(q, 0) qnorm = util.deflate_long(q, 0)
qhbyte = ord(qnorm[0]) qhbyte = ord(qnorm[0])
bytes = len(qnorm) byte_count = len(qnorm)
qmask = 0xff qmask = 0xff
while not (qhbyte & 0x80): while not (qhbyte & 0x80):
qhbyte <<= 1 qhbyte <<= 1
qmask >>= 1 qmask >>= 1
while True: while True:
x_bytes = self.transport.rng.read(bytes)
x_bytes = chr(ord(x_bytes[0]) & qmask) + x_bytes[1:] x_bytes = chr(ord(x_bytes[0]) & qmask) + x_bytes[1:]
x_bytes = self.transport.rng.read(byte_count)
x = util.inflate_long(x_bytes, 1) x = util.inflate_long(x_bytes, 1)
if (x > 1) and (x < q): if (x > 1) and (x < q):
break break

View File

@ -214,7 +214,8 @@ class Packetizer (object):
n -= len(x) n -= len(x)
except socket.timeout: except socket.timeout:
got_timeout = True got_timeout = True
except socket.error, e: except socket.error:
e = sys.exc_info()[1]
# on Linux, sometimes instead of socket.timeout, we get # on Linux, sometimes instead of socket.timeout, we get
# EAGAIN. this is a bug in recent (> 2.6.9) kernels but # EAGAIN. this is a bug in recent (> 2.6.9) kernels but
# we need to work around it. # we need to work around it.
@ -243,7 +244,8 @@ class Packetizer (object):
n = self.__socket.send(out) n = self.__socket.send(out)
except socket.timeout: except socket.timeout:
retry_write = True retry_write = True
except socket.error, e: except socket.error:
e = sys.exc_info()[1]
if (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EAGAIN): if (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EAGAIN):
retry_write = True retry_write = True
elif (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR): elif (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR):
@ -468,7 +470,8 @@ class Packetizer (object):
break break
except socket.timeout: except socket.timeout:
pass pass
except EnvironmentError, e: except EnvironmentError:
e = sys.exc_info()[1]
if ((type(e.args) is tuple) and (len(e.args) > 0) and if ((type(e.args) is tuple) and (len(e.args) > 0) and
(e.args[0] == errno.EINTR)): (e.args[0] == errno.EINTR)):
pass pass

View File

@ -304,8 +304,8 @@ class PKey (object):
# if we trudged to the end of the file, just try to cope. # if we trudged to the end of the file, just try to cope.
try: try:
data = base64.decodestring(''.join(lines[start:end])) data = base64.decodestring(''.join(lines[start:end]))
except base64.binascii.Error, e: except base64.binascii.Error:
raise SSHException('base64 decoding error: ' + str(e)) raise SSHException('base64 decoding error: ' + str(sys.exc_info()[1]))
if 'proc-type' not in headers: if 'proc-type' not in headers:
# unencryped: done # unencryped: done
return data return data

View File

@ -47,7 +47,7 @@ def _generate_prime(bits, rng):
def _roll_random(rng, n): def _roll_random(rng, n):
"returns a random # from 0 to N-1" "returns a random # from 0 to N-1"
bits = util.bit_length(n-1) bits = util.bit_length(n-1)
bytes = (bits + 7) // 8 byte_count = (bits + 7) // 8
hbyte_mask = pow(2, bits % 8) - 1 hbyte_mask = pow(2, bits % 8) - 1
# so here's the plan: # so here's the plan:
@ -57,7 +57,7 @@ def _roll_random(rng, n):
# fits, so i can't guarantee that this loop will ever finish, but the odds # fits, so i can't guarantee that this loop will ever finish, but the odds
# of it looping forever should be infinitesimal. # of it looping forever should be infinitesimal.
while True: while True:
x = rng.read(bytes) x = rng.read(byte_count)
if hbyte_mask > 0: if hbyte_mask > 0:
x = chr(ord(x[0]) & hbyte_mask) + x[1:] x = chr(ord(x[0]) & hbyte_mask) + x[1:]
num = util.inflate_long(x, 1) num = util.inflate_long(x, 1)
@ -125,8 +125,7 @@ class ModulusPack (object):
f.close() f.close()
def get_modulus(self, min, prefer, max): def get_modulus(self, min, prefer, max):
bitsizes = self.pack.keys() bitsizes = sorted(self.pack.keys(), key=hash)
bitsizes.sort()
if len(bitsizes) == 0: if len(bitsizes) == 0:
raise SSHException('no moduli available') raise SSHException('no moduli available')
good = -1 good = -1

View File

@ -60,12 +60,13 @@ class ProxyCommand(object):
""" """
try: try:
self.process.stdin.write(content) self.process.stdin.write(content)
except IOError, e: except IOError:
e = sys.exc_info()[1]
# There was a problem with the child process. It probably # There was a problem with the child process. It probably
# died and we can't proceed. The best option here is to # died and we can't proceed. The best option here is to
# raise an exception informing the user that the informed # raise an exception informing the user that the informed
# ProxyCommand is not working. # ProxyCommand is not working.
raise BadProxyCommand(' '.join(self.cmd), e.strerror) raise ProxyCommandFailure(' '.join(self.cmd), e.strerror)
return len(content) return len(content)
def recv(self, size): def recv(self, size):
@ -80,8 +81,9 @@ class ProxyCommand(object):
""" """
try: try:
return os.read(self.process.stdout.fileno(), size) return os.read(self.process.stdout.fileno(), size)
except IOError, e: except IOError:
raise BadProxyCommand(' '.join(self.cmd), e.strerror) e = sys.exc_info()[1]
raise ProxyCommandFailure(' '.join(self.cmd), e.strerror)
def close(self): def close(self):
os.kill(self.process.pid, signal.SIGTERM) os.kill(self.process.pid, signal.SIGTERM)

View File

@ -623,7 +623,8 @@ class SubsystemHandler (threading.Thread):
try: try:
self.__transport._log(DEBUG, 'Starting handler for subsystem %s' % self.__name) self.__transport._log(DEBUG, 'Starting handler for subsystem %s' % self.__name)
self.start_subsystem(self.__name, self.__transport, self.__channel) self.start_subsystem(self.__name, self.__transport, self.__channel)
except Exception, e: except Exception:
e = sys.exc_info()[1]
self.__transport._log(ERROR, 'Exception in subsystem handler for "%s": %s' % self.__transport._log(ERROR, 'Exception in subsystem handler for "%s": %s' %
(self.__name, str(e))) (self.__name, str(e)))
self.__transport._log(ERROR, util.tb_strings()) self.__transport._log(ERROR, util.tb_strings())

View File

@ -143,7 +143,7 @@ class SFTPAttributes (object):
msg.add_int(long(self.st_mtime)) msg.add_int(long(self.st_mtime))
if self._flags & self.FLAG_EXTENDED: if self._flags & self.FLAG_EXTENDED:
msg.add_int(len(self.attr)) msg.add_int(len(self.attr))
for key, val in self.attr.iteritems(): for key, val in self.attr.items():
msg.add_string(key) msg.add_string(key)
msg.add_string(val) msg.add_string(val)
return return
@ -158,7 +158,7 @@ class SFTPAttributes (object):
out += 'mode=' + oct(self.st_mode) + ' ' out += 'mode=' + oct(self.st_mode) + ' '
if (self.st_atime is not None) and (self.st_mtime is not None): if (self.st_atime is not None) and (self.st_mtime is not None):
out += 'atime=%d mtime=%d ' % (self.st_atime, self.st_mtime) out += 'atime=%d mtime=%d ' % (self.st_atime, self.st_mtime)
for k, v in self.attr.iteritems(): for k, v in self.attr.items():
out += '"%s"=%r ' % (str(k), v) out += '"%s"=%r ' % (str(k), v)
out += ']' out += ']'
return out return out

View File

@ -85,7 +85,7 @@ class SFTPClient (BaseSFTP):
self.ultra_debug = transport.get_hexdump() self.ultra_debug = transport.get_hexdump()
try: try:
server_version = self._send_version() server_version = self._send_version()
except EOFError, x: except EOFError:
raise SSHException('EOF during negotiation') raise SSHException('EOF during negotiation')
self._log(INFO, 'Opened sftp connection (server version %d)' % server_version) self._log(INFO, 'Opened sftp connection (server version %d)' % server_version)
@ -178,7 +178,7 @@ class SFTPClient (BaseSFTP):
while True: while True:
try: try:
t, msg = self._request(CMD_READDIR, handle) t, msg = self._request(CMD_READDIR, handle)
except EOFError, e: except EOFError:
# done with handle # done with handle
break break
if t != CMD_NAME: if t != CMD_NAME:
@ -717,8 +717,8 @@ class SFTPClient (BaseSFTP):
while True: while True:
try: try:
t, data = self._read_packet() t, data = self._read_packet()
except EOFError, e: except EOFError:
raise SSHException('Server connection dropped: %s' % (str(e),)) raise SSHException('Server connection dropped: %s' % str(sys.exc_info()[1]))
msg = Message(data) msg = Message(data)
num = msg.get_int() num = msg.get_int()
if num not in self._expecting: if num not in self._expecting:

View File

@ -94,7 +94,7 @@ class SFTPFile (BufferedFile):
k = [i for i in self._prefetch_reads if i[0] <= offset] k = [i for i in self._prefetch_reads if i[0] <= offset]
if len(k) == 0: if len(k) == 0:
return False return False
k.sort(lambda x, y: cmp(x[0], y[0])) k.sort(key=hash)
buf_offset, buf_size = k[-1] buf_offset, buf_size = k[-1]
if buf_offset + buf_size <= offset: if buf_offset + buf_size <= offset:
# prefetch request ends before this one begins # prefetch request ends before this one begins
@ -464,8 +464,8 @@ class SFTPFile (BufferedFile):
# save exception and re-raise it on next file operation # save exception and re-raise it on next file operation
try: try:
self.sftp._convert_status(msg) self.sftp._convert_status(msg)
except Exception, x: except Exception:
self._saved_exception = x self._saved_exception = sys.exc_info()[1]
return return
if t != CMD_DATA: if t != CMD_DATA:
raise SFTPError('Expected data') raise SFTPError('Expected data')

View File

@ -100,7 +100,8 @@ class SFTPHandle (object):
readfile.seek(offset) readfile.seek(offset)
self.__tell = offset self.__tell = offset
data = readfile.read(length) data = readfile.read(length)
except IOError, e: except IOError:
e = sys.exc_info()[1]
self.__tell = None self.__tell = None
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
self.__tell += len(data) self.__tell += len(data)
@ -139,7 +140,8 @@ class SFTPHandle (object):
self.__tell = offset self.__tell = offset
writefile.write(data) writefile.write(data)
writefile.flush() writefile.flush()
except IOError, e: except IOError:
e = sys.exc_info()[1]
self.__tell = None self.__tell = None
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
if self.__tell is not None: if self.__tell is not None:

View File

@ -92,7 +92,8 @@ class SFTPServer (BaseSFTP, SubsystemHandler):
except EOFError: except EOFError:
self._log(DEBUG, 'EOF -- end of session') self._log(DEBUG, 'EOF -- end of session')
return return
except Exception, e: except Exception:
e = sys.exc_info()[1]
self._log(DEBUG, 'Exception on channel: ' + str(e)) self._log(DEBUG, 'Exception on channel: ' + str(e))
self._log(DEBUG, util.tb_strings()) self._log(DEBUG, util.tb_strings())
return return
@ -100,7 +101,8 @@ class SFTPServer (BaseSFTP, SubsystemHandler):
request_number = msg.get_int() request_number = msg.get_int()
try: try:
self._process(t, request_number, msg) self._process(t, request_number, msg)
except Exception, e: except Exception:
e = sys.exc_info()[1]
self._log(DEBUG, 'Exception in server processing: ' + str(e)) self._log(DEBUG, 'Exception in server processing: ' + str(e))
self._log(DEBUG, util.tb_strings()) self._log(DEBUG, util.tb_strings())
# send some kind of failure message, at least # send some kind of failure message, at least
@ -113,9 +115,9 @@ class SFTPServer (BaseSFTP, SubsystemHandler):
self.server.session_ended() self.server.session_ended()
super(SFTPServer, self).finish_subsystem() super(SFTPServer, self).finish_subsystem()
# close any file handles that were left open (so we can return them to the OS quickly) # close any file handles that were left open (so we can return them to the OS quickly)
for f in self.file_table.itervalues(): for f in self.file_table.values():
f.close() f.close()
for f in self.folder_table.itervalues(): for f in self.folder_table.values():
f.close() f.close()
self.file_table = {} self.file_table = {}
self.folder_table = {} self.folder_table = {}

View File

@ -177,7 +177,7 @@ class ChannelMap (object):
def values(self): def values(self):
self._lock.acquire() self._lock.acquire()
try: try:
return self._map.values() return list(self._map.values())
finally: finally:
self._lock.release() self._lock.release()
@ -294,8 +294,8 @@ class Transport (threading.Thread):
sock = socket.socket(af, socket.SOCK_STREAM) sock = socket.socket(af, socket.SOCK_STREAM)
try: try:
retry_on_signal(lambda: sock.connect((hostname, port))) retry_on_signal(lambda: sock.connect((hostname, port)))
except socket.error, e: except socket.error:
reason = str(e) reason = str(sys.exc_info()[1])
else: else:
break break
else: else:
@ -616,7 +616,7 @@ class Transport (threading.Thread):
if not self.active: if not self.active:
return return
self.stop_thread() self.stop_thread()
for chan in self._channels.values(): for chan in list(self._channels.values()):
chan._unlink() chan._unlink()
self.sock.close() self.sock.close()
@ -691,7 +691,7 @@ class Transport (threading.Thread):
""" """
return self.open_channel('auth-agent@openssh.com') return self.open_channel('auth-agent@openssh.com')
def open_forwarded_tcpip_channel(self, (src_addr, src_port), (dest_addr, dest_port)): def open_forwarded_tcpip_channel(self, src_addr_port, dest_addr_port):
""" """
Request a new channel back to the client, of type C{"forwarded-tcpip"}. Request a new channel back to the client, of type C{"forwarded-tcpip"}.
This is used after a client has requested port forwarding, for sending This is used after a client has requested port forwarding, for sending
@ -702,6 +702,8 @@ class Transport (threading.Thread):
@param dest_addr: local (server) connected address @param dest_addr: local (server) connected address
@param dest_port: local (server) connected port @param dest_port: local (server) connected port
""" """
src_addr, src_port = src_addr_port
dest_addr, dest_port = dest_addr_port
return self.open_channel('forwarded-tcpip', (dest_addr, dest_port), (src_addr, src_port)) return self.open_channel('forwarded-tcpip', (dest_addr, dest_port), (src_addr, src_port))
def open_channel(self, kind, dest_addr=None, src_addr=None): def open_channel(self, kind, dest_addr=None, src_addr=None):
@ -811,7 +813,9 @@ class Transport (threading.Thread):
if port == 0: if port == 0:
port = response.get_int() port = response.get_int()
if handler is None: if handler is None:
def default_handler(channel, (src_addr, src_port), (dest_addr, dest_port)): def default_handler(channel, src_addr_port, dest_addr_port):
#src_addr, src_port = src_addr_port
#dest_addr, dest_port = dest_addr_port
self._queue_incoming_channel(channel) self._queue_incoming_channel(channel)
handler = default_handler handler = default_handler
self._tcp_handler = handler self._tcp_handler = handler
@ -845,22 +849,22 @@ class Transport (threading.Thread):
""" """
return SFTPClient.from_transport(self) return SFTPClient.from_transport(self)
def send_ignore(self, bytes=None): def send_ignore(self, byte_count=None):
""" """
Send a junk packet across the encrypted link. This is sometimes used Send a junk packet across the encrypted link. This is sometimes used
to add "noise" to a connection to confuse would-be attackers. It can to add "noise" to a connection to confuse would-be attackers. It can
also be used as a keep-alive for long lived connections traversing also be used as a keep-alive for long lived connections traversing
firewalls. firewalls.
@param bytes: the number of random bytes to send in the payload of the @param byte_count: the number of random bytes to send in the payload of the
ignored packet -- defaults to a random number from 10 to 41. ignored packet -- defaults to a random number from 10 to 41.
@type bytes: int @type byte_count: int
""" """
m = Message() m = Message()
m.add_byte(chr(MSG_IGNORE)) m.add_byte(chr(MSG_IGNORE))
if bytes is None: if byte_count is None:
bytes = (ord(rng.read(1)) % 32) + 10 byte_count = (byte_ord(rng.read(1)) % 32) + 10
m.add_bytes(rng.read(bytes)) m.add_bytes(rng.read(byte_count))
self._send_user_message(m) self._send_user_message(m)
def renegotiate_keys(self): def renegotiate_keys(self):
@ -1181,7 +1185,8 @@ class Transport (threading.Thread):
return [] return []
try: try:
return self.auth_handler.wait_for_response(my_event) return self.auth_handler.wait_for_response(my_event)
except BadAuthenticationType, x: except BadAuthenticationType:
x = sys.exc_info()[1]
# if password auth isn't allowed, but keyboard-interactive *is*, try to fudge it # if password auth isn't allowed, but keyboard-interactive *is*, try to fudge it
if not fallback or ('keyboard-interactive' not in x.allowed_types): if not fallback or ('keyboard-interactive' not in x.allowed_types):
raise raise
@ -1197,7 +1202,7 @@ class Transport (threading.Thread):
return [] return []
return [ password ] return [ password ]
return self.auth_interactive(username, handler) return self.auth_interactive(username, handler)
except SSHException, ignored: except SSHException:
# attempt failed; just raise the original exception # attempt failed; just raise the original exception
raise x raise x
return None return None
@ -1513,7 +1518,7 @@ class Transport (threading.Thread):
# only called if a channel has turned on x11 forwarding # only called if a channel has turned on x11 forwarding
if handler is None: if handler is None:
# by default, use the same mechanism as accept() # by default, use the same mechanism as accept()
def default_handler(channel, (src_addr, src_port)): def default_handler(channel, src_addr_port):
self._queue_incoming_channel(channel) self._queue_incoming_channel(channel)
self._x11_handler = default_handler self._x11_handler = default_handler
else: else:
@ -1604,22 +1609,26 @@ class Transport (threading.Thread):
msg.add_byte(chr(MSG_UNIMPLEMENTED)) msg.add_byte(chr(MSG_UNIMPLEMENTED))
msg.add_int(m.seqno) msg.add_int(m.seqno)
self._send_message(msg) self._send_message(msg)
except SSHException, e: except SSHException:
e = sys.exc_info()[1]
self._log(ERROR, 'Exception: ' + str(e)) self._log(ERROR, 'Exception: ' + str(e))
self._log(ERROR, util.tb_strings()) self._log(ERROR, util.tb_strings())
self.saved_exception = e self.saved_exception = e
except EOFError, e: except EOFError:
e = sys.exc_info()[1]
self._log(DEBUG, 'EOF in transport thread') self._log(DEBUG, 'EOF in transport thread')
#self._log(DEBUG, util.tb_strings()) #self._log(DEBUG, util.tb_strings())
self.saved_exception = e self.saved_exception = e
except socket.error, e: except socket.error:
e = sys.exc_info()[1]
if type(e.args) is tuple: if type(e.args) is tuple:
emsg = '%s (%d)' % (e.args[1], e.args[0]) emsg = '%s (%d)' % (e.args[1], e.args[0])
else: else:
emsg = e.args emsg = e.args
self._log(ERROR, 'Socket exception: ' + emsg) self._log(ERROR, 'Socket exception: ' + emsg)
self.saved_exception = e self.saved_exception = e
except Exception, e: except Exception:
e = sys.exc_info()[1]
self._log(ERROR, 'Unknown exception: ' + str(e)) self._log(ERROR, 'Unknown exception: ' + str(e))
self._log(ERROR, util.tb_strings()) self._log(ERROR, util.tb_strings())
self.saved_exception = e self.saved_exception = e
@ -1679,7 +1688,8 @@ class Transport (threading.Thread):
buf = self.packetizer.readline(timeout) buf = self.packetizer.readline(timeout)
except ProxyCommandFailure: except ProxyCommandFailure:
raise raise
except Exception, x: except Exception:
x = sys.exc_info()[1]
raise SSHException('Error reading SSH protocol banner' + str(x)) raise SSHException('Error reading SSH protocol banner' + str(x))
if buf[:4] == 'SSH-': if buf[:4] == 'SSH-':
break break
@ -1690,7 +1700,7 @@ class Transport (threading.Thread):
self.remote_version = buf self.remote_version = buf
# pull off any attached comment # pull off any attached comment
comment = '' comment = ''
i = string.find(buf, ' ') i = buf.find(' ')
if i >= 0: if i >= 0:
comment = buf[i+1:] comment = buf[i+1:]
buf = buf[:i] buf = buf[:i]
@ -1774,19 +1784,19 @@ class Transport (threading.Thread):
# as a server, we pick the first item in the client's list that we support. # as a server, we pick the first item in the client's list that we support.
# as a client, we pick the first item in our list that the server supports. # as a client, we pick the first item in our list that the server supports.
if self.server_mode: if self.server_mode:
agreed_kex = filter(self._preferred_kex.__contains__, kex_algo_list) agreed_kex = list(filter(self._preferred_kex.__contains__, kex_algo_list))
else: else:
agreed_kex = filter(kex_algo_list.__contains__, self._preferred_kex) agreed_kex = list(filter(kex_algo_list.__contains__, self._preferred_kex))
if len(agreed_kex) == 0: if len(agreed_kex) == 0:
raise SSHException('Incompatible ssh peer (no acceptable kex algorithm)') raise SSHException('Incompatible ssh peer (no acceptable kex algorithm)')
self.kex_engine = self._kex_info[agreed_kex[0]](self) self.kex_engine = self._kex_info[agreed_kex[0]](self)
if self.server_mode: if self.server_mode:
available_server_keys = filter(self.server_key_dict.keys().__contains__, available_server_keys = list(filter(list(self.server_key_dict.keys()).__contains__,
self._preferred_keys) self._preferred_keys))
agreed_keys = filter(available_server_keys.__contains__, server_key_algo_list) agreed_keys = list(filter(available_server_keys.__contains__, server_key_algo_list))
else: else:
agreed_keys = filter(server_key_algo_list.__contains__, self._preferred_keys) agreed_keys = list(filter(server_key_algo_list.__contains__, self._preferred_keys))
if len(agreed_keys) == 0: if len(agreed_keys) == 0:
raise SSHException('Incompatible ssh peer (no acceptable host key)') raise SSHException('Incompatible ssh peer (no acceptable host key)')
self.host_key_type = agreed_keys[0] self.host_key_type = agreed_keys[0]
@ -1794,15 +1804,15 @@ class Transport (threading.Thread):
raise SSHException('Incompatible ssh peer (can\'t match requested host key type)') raise SSHException('Incompatible ssh peer (can\'t match requested host key type)')
if self.server_mode: if self.server_mode:
agreed_local_ciphers = filter(self._preferred_ciphers.__contains__, agreed_local_ciphers = list(filter(self._preferred_ciphers.__contains__,
server_encrypt_algo_list) server_encrypt_algo_list))
agreed_remote_ciphers = filter(self._preferred_ciphers.__contains__, agreed_remote_ciphers = list(filter(self._preferred_ciphers.__contains__,
client_encrypt_algo_list) client_encrypt_algo_list))
else: else:
agreed_local_ciphers = filter(client_encrypt_algo_list.__contains__, agreed_local_ciphers = list(filter(client_encrypt_algo_list.__contains__,
self._preferred_ciphers) self._preferred_ciphers))
agreed_remote_ciphers = filter(server_encrypt_algo_list.__contains__, agreed_remote_ciphers = list(filter(server_encrypt_algo_list.__contains__,
self._preferred_ciphers) self._preferred_ciphers))
if (len(agreed_local_ciphers) == 0) or (len(agreed_remote_ciphers) == 0): if (len(agreed_local_ciphers) == 0) or (len(agreed_remote_ciphers) == 0):
raise SSHException('Incompatible ssh server (no acceptable ciphers)') raise SSHException('Incompatible ssh server (no acceptable ciphers)')
self.local_cipher = agreed_local_ciphers[0] self.local_cipher = agreed_local_ciphers[0]
@ -1810,22 +1820,22 @@ class Transport (threading.Thread):
self._log(DEBUG, 'Ciphers agreed: local=%s, remote=%s' % (self.local_cipher, self.remote_cipher)) self._log(DEBUG, 'Ciphers agreed: local=%s, remote=%s' % (self.local_cipher, self.remote_cipher))
if self.server_mode: if self.server_mode:
agreed_remote_macs = filter(self._preferred_macs.__contains__, client_mac_algo_list) agreed_remote_macs = list(filter(self._preferred_macs.__contains__, client_mac_algo_list))
agreed_local_macs = filter(self._preferred_macs.__contains__, server_mac_algo_list) agreed_local_macs = list(filter(self._preferred_macs.__contains__, server_mac_algo_list))
else: else:
agreed_local_macs = filter(client_mac_algo_list.__contains__, self._preferred_macs) agreed_local_macs = list(filter(client_mac_algo_list.__contains__, self._preferred_macs))
agreed_remote_macs = filter(server_mac_algo_list.__contains__, self._preferred_macs) agreed_remote_macs = list(filter(server_mac_algo_list.__contains__, self._preferred_macs))
if (len(agreed_local_macs) == 0) or (len(agreed_remote_macs) == 0): if (len(agreed_local_macs) == 0) or (len(agreed_remote_macs) == 0):
raise SSHException('Incompatible ssh server (no acceptable macs)') raise SSHException('Incompatible ssh server (no acceptable macs)')
self.local_mac = agreed_local_macs[0] self.local_mac = agreed_local_macs[0]
self.remote_mac = agreed_remote_macs[0] self.remote_mac = agreed_remote_macs[0]
if self.server_mode: if self.server_mode:
agreed_remote_compression = filter(self._preferred_compression.__contains__, client_compress_algo_list) agreed_remote_compression = list(filter(self._preferred_compression.__contains__, client_compress_algo_list))
agreed_local_compression = filter(self._preferred_compression.__contains__, server_compress_algo_list) agreed_local_compression = list(filter(self._preferred_compression.__contains__, server_compress_algo_list))
else: else:
agreed_local_compression = filter(client_compress_algo_list.__contains__, self._preferred_compression) agreed_local_compression = list(filter(client_compress_algo_list.__contains__, self._preferred_compression))
agreed_remote_compression = filter(server_compress_algo_list.__contains__, self._preferred_compression) agreed_remote_compression = list(filter(server_compress_algo_list.__contains__, self._preferred_compression))
if (len(agreed_local_compression) == 0) or (len(agreed_remote_compression) == 0): if (len(agreed_local_compression) == 0) or (len(agreed_remote_compression) == 0):
raise SSHException('Incompatible ssh server (no acceptable compression) %r %r %r' % (agreed_local_compression, agreed_remote_compression, self._preferred_compression)) raise SSHException('Incompatible ssh server (no acceptable compression) %r %r %r' % (agreed_local_compression, agreed_remote_compression, self._preferred_compression))
self.local_compression = agreed_local_compression[0] self.local_compression = agreed_local_compression[0]

View File

@ -276,13 +276,14 @@ def retry_on_signal(function):
while True: while True:
try: try:
return function() return function()
except EnvironmentError, e: except EnvironmentError:
e = sys.exc_info()[1]
if e.errno != errno.EINTR: if e.errno != errno.EINTR:
raise raise
class Counter (object): class Counter (object):
"""Stateful counter for CTR mode crypto""" """Stateful counter for CTR mode crypto"""
def __init__(self, nbits, initial_value=1L, overflow=0L): def __init__(self, nbits, initial_value=long_one, overflow=long_zero):
self.blocksize = nbits / 8 self.blocksize = nbits / 8
self.overflow = overflow self.overflow = overflow
# start with value - 1 so we don't have to store intermediate values when counting # start with value - 1 so we don't have to store intermediate values when counting

View File

@ -40,7 +40,8 @@ class StubSFTPHandle (SFTPHandle):
def stat(self): def stat(self):
try: try:
return SFTPAttributes.from_stat(os.fstat(self.readfile.fileno())) return SFTPAttributes.from_stat(os.fstat(self.readfile.fileno()))
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
def chattr(self, attr): def chattr(self, attr):
@ -49,7 +50,8 @@ class StubSFTPHandle (SFTPHandle):
try: try:
SFTPServer.set_file_attr(self.filename, attr) SFTPServer.set_file_attr(self.filename, attr)
return SFTP_OK return SFTP_OK
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
@ -71,21 +73,24 @@ class StubSFTPServer (SFTPServerInterface):
attr.filename = fname attr.filename = fname
out.append(attr) out.append(attr)
return out return out
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
def stat(self, path): def stat(self, path):
path = self._realpath(path) path = self._realpath(path)
try: try:
return SFTPAttributes.from_stat(os.stat(path)) return SFTPAttributes.from_stat(os.stat(path))
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
def lstat(self, path): def lstat(self, path):
path = self._realpath(path) path = self._realpath(path)
try: try:
return SFTPAttributes.from_stat(os.lstat(path)) return SFTPAttributes.from_stat(os.lstat(path))
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
def open(self, path, flags, attr): def open(self, path, flags, attr):
@ -100,7 +105,8 @@ class StubSFTPServer (SFTPServerInterface):
# os.open() defaults to 0777 which is # os.open() defaults to 0777 which is
# an odd default mode for files # an odd default mode for files
fd = os.open(path, flags, 0666) fd = os.open(path, flags, 0666)
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
if (flags & os.O_CREAT) and (attr is not None): if (flags & os.O_CREAT) and (attr is not None):
attr._flags &= ~attr.FLAG_PERMISSIONS attr._flags &= ~attr.FLAG_PERMISSIONS
@ -120,7 +126,8 @@ class StubSFTPServer (SFTPServerInterface):
fstr = 'rb' fstr = 'rb'
try: try:
f = os.fdopen(fd, fstr) f = os.fdopen(fd, fstr)
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
fobj = StubSFTPHandle(flags) fobj = StubSFTPHandle(flags)
fobj.filename = path fobj.filename = path
@ -132,7 +139,8 @@ class StubSFTPServer (SFTPServerInterface):
path = self._realpath(path) path = self._realpath(path)
try: try:
os.remove(path) os.remove(path)
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
return SFTP_OK return SFTP_OK
@ -141,7 +149,8 @@ class StubSFTPServer (SFTPServerInterface):
newpath = self._realpath(newpath) newpath = self._realpath(newpath)
try: try:
os.rename(oldpath, newpath) os.rename(oldpath, newpath)
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
return SFTP_OK return SFTP_OK
@ -151,7 +160,8 @@ class StubSFTPServer (SFTPServerInterface):
os.mkdir(path) os.mkdir(path)
if attr is not None: if attr is not None:
SFTPServer.set_file_attr(path, attr) SFTPServer.set_file_attr(path, attr)
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
return SFTP_OK return SFTP_OK
@ -159,7 +169,8 @@ class StubSFTPServer (SFTPServerInterface):
path = self._realpath(path) path = self._realpath(path)
try: try:
os.rmdir(path) os.rmdir(path)
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
return SFTP_OK return SFTP_OK
@ -167,7 +178,8 @@ class StubSFTPServer (SFTPServerInterface):
path = self._realpath(path) path = self._realpath(path)
try: try:
SFTPServer.set_file_attr(path, attr) SFTPServer.set_file_attr(path, attr)
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
return SFTP_OK return SFTP_OK
@ -187,7 +199,8 @@ class StubSFTPServer (SFTPServerInterface):
target_path = '<error>' target_path = '<error>'
try: try:
os.symlink(target_path, path) os.symlink(target_path, path)
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
return SFTP_OK return SFTP_OK
@ -195,7 +208,8 @@ class StubSFTPServer (SFTPServerInterface):
path = self._realpath(path) path = self._realpath(path)
try: try:
symlink = os.readlink(path) symlink = os.readlink(path)
except OSError, e: except OSError:
e = sys.exc_info()[1]
return SFTPServer.convert_errno(e.errno) return SFTPServer.convert_errno(e.errno)
# if it's absolute, remove the root # if it's absolute, remove the root
if os.path.isabs(symlink): if os.path.isabs(symlink):

View File

@ -249,7 +249,7 @@ class TransportTest(ParamikoTest):
try: try:
chan.exec_command('no') chan.exec_command('no')
self.assert_(False) self.assert_(False)
except SSHException, x: except SSHException:
pass pass
chan = self.tc.open_session() chan = self.tc.open_session()
@ -302,7 +302,8 @@ class TransportTest(ParamikoTest):
try: try:
chan = self.tc.open_channel('bogus') chan = self.tc.open_channel('bogus')
self.fail('expected exception') self.fail('expected exception')
except ChannelException, x: except ChannelException:
x = sys.exc_info()[1]
self.assert_(x.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED) self.assert_(x.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED)
def test_9_exit_status(self): def test_9_exit_status(self):
@ -444,7 +445,8 @@ class TransportTest(ParamikoTest):
schan = self.ts.accept(1.0) schan = self.ts.accept(1.0)
requested = [] requested = []
def handler(c, (addr, port)): def handler(c, addr_port):
addr, port = addr_port
requested.append((addr, port)) requested.append((addr, port))
self.tc._queue_incoming_channel(c) self.tc._queue_incoming_channel(c)
@ -479,9 +481,9 @@ class TransportTest(ParamikoTest):
schan = self.ts.accept(1.0) schan = self.ts.accept(1.0)
requested = [] requested = []
def handler(c, (origin_addr, origin_port), (server_addr, server_port)): def handler(c, origin_addr_port, server_addr_port):
requested.append((origin_addr, origin_port)) requested.append(origin_addr_port)
requested.append((server_addr, server_port)) requested.append(server_addr_port)
self.tc._queue_incoming_channel(c) self.tc._queue_incoming_channel(c)
port = self.tc.request_port_forward('127.0.0.1', 0, handler) port = self.tc.request_port_forward('127.0.0.1', 0, handler)

View File

@ -65,7 +65,7 @@ class UtilTest(ParamikoTest):
""" """
verify that all the classes can be imported from paramiko. verify that all the classes can be imported from paramiko.
""" """
symbols = globals().keys() symbols = list(globals().keys())
self.assertTrue('Transport' in symbols) self.assertTrue('Transport' in symbols)
self.assertTrue('SSHClient' in symbols) self.assertTrue('SSHClient' in symbols)
self.assertTrue('MissingHostKeyPolicy' in symbols) self.assertTrue('MissingHostKeyPolicy' in symbols)
@ -148,8 +148,8 @@ class UtilTest(ParamikoTest):
try: try:
hostdict = paramiko.util.load_host_keys('hostfile.temp') hostdict = paramiko.util.load_host_keys('hostfile.temp')
self.assertEquals(2, len(hostdict)) self.assertEquals(2, len(hostdict))
self.assertEquals(1, len(hostdict.values()[0])) self.assertEquals(1, len(list(hostdict.values())[0]))
self.assertEquals(1, len(hostdict.values()[1])) self.assertEquals(1, len(list(hostdict.values())[1]))
fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper()
self.assertEquals('E6684DB30E109B67B70FF1DC5C7F1363', fp) self.assertEquals('E6684DB30E109B67B70FF1DC5C7F1363', fp)
finally: finally: