From 2ea352b8baf1037bd22fc79146ef646c163a7692 Mon Sep 17 00:00:00 2001 From: Scott Maxwell Date: Wed, 30 Oct 2013 16:46:33 -0700 Subject: [PATCH] Fix dict iters, sorts, exceptions, bytes renames and tuple args --- paramiko/__init__.py | 2 +- paramiko/auth_handler.py | 3 +- paramiko/channel.py | 4 +- paramiko/client.py | 26 +++++------ paramiko/config.py | 2 +- paramiko/dsskey.py | 4 +- paramiko/file.py | 6 +-- paramiko/hostkeys.py | 4 +- paramiko/kex_gex.py | 4 +- paramiko/packet.py | 9 ++-- paramiko/pkey.py | 4 +- paramiko/primes.py | 7 ++- paramiko/proxy.py | 10 +++-- paramiko/server.py | 3 +- paramiko/sftp_attr.py | 4 +- paramiko/sftp_client.py | 8 ++-- paramiko/sftp_file.py | 6 +-- paramiko/sftp_handle.py | 6 ++- paramiko/sftp_server.py | 10 +++-- paramiko/transport.py | 96 ++++++++++++++++++++++------------------ paramiko/util.py | 5 ++- tests/stub_sftp.py | 42 ++++++++++++------ tests/test_transport.py | 14 +++--- tests/test_util.py | 6 +-- 24 files changed, 160 insertions(+), 125 deletions(-) diff --git a/paramiko/__init__.py b/paramiko/__init__.py index 86e0bc6..160ed39 100644 --- a/paramiko/__init__.py +++ b/paramiko/__init__.py @@ -90,7 +90,7 @@ from paramiko.config import SSHConfig from paramiko.proxy import ProxyCommand # 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': # classobj for exceptions :/ c.__module__ = __name__ diff --git a/paramiko/auth_handler.py b/paramiko/auth_handler.py index acb7c8b..de0b205 100644 --- a/paramiko/auth_handler.py +++ b/paramiko/auth_handler.py @@ -308,7 +308,8 @@ class AuthHandler (object): keyblob = m.get_string() try: 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)) key = None except: diff --git a/paramiko/channel.py b/paramiko/channel.py index d1e6333..d351768 100644 --- a/paramiko/channel.py +++ b/paramiko/channel.py @@ -615,7 +615,7 @@ class Channel (object): """ try: out = self.in_buffer.read(nbytes, self.timeout) - except PipeTimeout, e: + except PipeTimeout: raise socket.timeout() ack = self._check_add_window(len(out)) @@ -665,7 +665,7 @@ class Channel (object): """ try: out = self.in_stderr_buffer.read(nbytes, self.timeout) - except PipeTimeout, e: + except PipeTimeout: raise socket.timeout() ack = self._check_add_window(len(out)) diff --git a/paramiko/client.py b/paramiko/client.py index c5a2d1a..98bb47f 100644 --- a/paramiko/client.py +++ b/paramiko/client.py @@ -193,8 +193,8 @@ class SSHClient (object): self.load_host_keys(self.known_hosts) f = open(filename, 'w') - for hostname, keys in self._host_keys.iteritems(): - for keytype, key in keys.iteritems(): + for hostname, keys in self._host_keys.items(): + for keytype, key in keys.items(): f.write('%s %s %s\n' % (hostname, keytype, key.get_base64())) f.close() @@ -452,8 +452,8 @@ class SSHClient (object): two_factor = (allowed_types == ['password']) if not two_factor: return - except SSHException, e: - saved_exception = e + except SSHException: + saved_exception = sys.exc_info()[1] if not two_factor: for key_filename in key_filenames: @@ -466,8 +466,8 @@ class SSHClient (object): if not two_factor: return break - except SSHException, e: - saved_exception = e + except SSHException: + saved_exception = sys.exc_info()[1] if not two_factor and allow_agent: if self._agent == None: @@ -482,8 +482,8 @@ class SSHClient (object): if not two_factor: return break - except SSHException, e: - saved_exception = e + except SSHException: + saved_exception = sys.exc_info()[1] if not two_factor: keyfiles = [] @@ -514,17 +514,15 @@ class SSHClient (object): if not two_factor: return break - except SSHException, e: - saved_exception = e - except IOError, e: - saved_exception = e + except (SSHException, IOError): + saved_exception = sys.exc_info()[1] if password is not None: try: self._transport.auth_password(username, password) return - except SSHException, e: - saved_exception = e + except SSHException: + saved_exception = sys.exc_info()[1] elif two_factor: raise SSHException('Two-factor authentication requires a password') diff --git a/paramiko/config.py b/paramiko/config.py index 1705de7..51415be 100644 --- a/paramiko/config.py +++ b/paramiko/config.py @@ -173,7 +173,7 @@ class SSHConfig (object): ret = {} for match in matches: - for key, value in match['config'].iteritems(): + for key, value in match['config'].items(): if key not in ret: # Create a copy of the original value, # else it will reference the original list diff --git a/paramiko/dsskey.py b/paramiko/dsskey.py index f6ecb2a..ff74488 100644 --- a/paramiko/dsskey.py +++ b/paramiko/dsskey.py @@ -184,8 +184,8 @@ class DSSKey (PKey): # DSAPrivateKey = { version = 0, p, q, g, y, x } try: keylist = BER(data).decode() - except BERException, x: - raise SSHException('Unable to parse key file: ' + str(x)) + except BERException: + 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): raise SSHException('not a valid DSA private key file (bad ber encoding)') self.p = keylist[1] diff --git a/paramiko/file.py b/paramiko/file.py index d177913..1a8d3ee 100644 --- a/paramiko/file.py +++ b/paramiko/file.py @@ -254,14 +254,14 @@ class BufferedFile (object): @rtype: list """ lines = [] - bytes = 0 + byte_count = 0 while True: line = self.readline() if len(line) == 0: break lines.append(line) - bytes += len(line) - if (sizehint is not None) and (bytes >= sizehint): + byte_count += len(line) + if (sizehint is not None) and (byte_count >= sizehint): break return lines diff --git a/paramiko/hostkeys.py b/paramiko/hostkeys.py index c0e58b0..f548263 100644 --- a/paramiko/hostkeys.py +++ b/paramiko/hostkeys.py @@ -91,8 +91,8 @@ class HostKeyEntry: log.info("Unable to handle key of type %s" % (keytype,)) return None - except binascii.Error, e: - raise InvalidHostKey(line, e) + except binascii.Error: + raise InvalidHostKey(line, sys.exc_info()[1]) return cls(names, key) from_line = classmethod(from_line) diff --git a/paramiko/kex_gex.py b/paramiko/kex_gex.py index c0455a1..669bd34 100644 --- a/paramiko/kex_gex.py +++ b/paramiko/kex_gex.py @@ -95,14 +95,14 @@ class KexGex (object): q = (self.p - 1) // 2 qnorm = util.deflate_long(q, 0) qhbyte = ord(qnorm[0]) - bytes = len(qnorm) + byte_count = len(qnorm) qmask = 0xff while not (qhbyte & 0x80): qhbyte <<= 1 qmask >>= 1 while True: - x_bytes = self.transport.rng.read(bytes) 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) if (x > 1) and (x < q): break diff --git a/paramiko/packet.py b/paramiko/packet.py index 6ab7363..3a26b6b 100644 --- a/paramiko/packet.py +++ b/paramiko/packet.py @@ -214,7 +214,8 @@ class Packetizer (object): n -= len(x) except socket.timeout: got_timeout = True - except socket.error, e: + except socket.error: + e = sys.exc_info()[1] # on Linux, sometimes instead of socket.timeout, we get # EAGAIN. this is a bug in recent (> 2.6.9) kernels but # we need to work around it. @@ -243,7 +244,8 @@ class Packetizer (object): n = self.__socket.send(out) except socket.timeout: 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): retry_write = True 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 except socket.timeout: pass - except EnvironmentError, e: + except EnvironmentError: + e = sys.exc_info()[1] if ((type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR)): pass diff --git a/paramiko/pkey.py b/paramiko/pkey.py index b1199df..d61809f 100644 --- a/paramiko/pkey.py +++ b/paramiko/pkey.py @@ -304,8 +304,8 @@ class PKey (object): # if we trudged to the end of the file, just try to cope. try: data = base64.decodestring(''.join(lines[start:end])) - except base64.binascii.Error, e: - raise SSHException('base64 decoding error: ' + str(e)) + except base64.binascii.Error: + raise SSHException('base64 decoding error: ' + str(sys.exc_info()[1])) if 'proc-type' not in headers: # unencryped: done return data diff --git a/paramiko/primes.py b/paramiko/primes.py index bf2b810..1dd87da 100644 --- a/paramiko/primes.py +++ b/paramiko/primes.py @@ -47,7 +47,7 @@ def _generate_prime(bits, rng): def _roll_random(rng, n): "returns a random # from 0 to N-1" bits = util.bit_length(n-1) - bytes = (bits + 7) // 8 + byte_count = (bits + 7) // 8 hbyte_mask = pow(2, bits % 8) - 1 # 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 # of it looping forever should be infinitesimal. while True: - x = rng.read(bytes) + x = rng.read(byte_count) if hbyte_mask > 0: x = chr(ord(x[0]) & hbyte_mask) + x[1:] num = util.inflate_long(x, 1) @@ -125,8 +125,7 @@ class ModulusPack (object): f.close() def get_modulus(self, min, prefer, max): - bitsizes = self.pack.keys() - bitsizes.sort() + bitsizes = sorted(self.pack.keys(), key=hash) if len(bitsizes) == 0: raise SSHException('no moduli available') good = -1 diff --git a/paramiko/proxy.py b/paramiko/proxy.py index a10feb0..43c4666 100644 --- a/paramiko/proxy.py +++ b/paramiko/proxy.py @@ -60,12 +60,13 @@ class ProxyCommand(object): """ try: 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 # died and we can't proceed. The best option here is to # raise an exception informing the user that the informed # ProxyCommand is not working. - raise BadProxyCommand(' '.join(self.cmd), e.strerror) + raise ProxyCommandFailure(' '.join(self.cmd), e.strerror) return len(content) def recv(self, size): @@ -80,8 +81,9 @@ class ProxyCommand(object): """ try: return os.read(self.process.stdout.fileno(), size) - except IOError, e: - raise BadProxyCommand(' '.join(self.cmd), e.strerror) + except IOError: + e = sys.exc_info()[1] + raise ProxyCommandFailure(' '.join(self.cmd), e.strerror) def close(self): os.kill(self.process.pid, signal.SIGTERM) diff --git a/paramiko/server.py b/paramiko/server.py index fdb4094..4b6e8b1 100644 --- a/paramiko/server.py +++ b/paramiko/server.py @@ -623,7 +623,8 @@ class SubsystemHandler (threading.Thread): try: self.__transport._log(DEBUG, 'Starting handler for subsystem %s' % self.__name) 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.__name, str(e))) self.__transport._log(ERROR, util.tb_strings()) diff --git a/paramiko/sftp_attr.py b/paramiko/sftp_attr.py index b459b04..84c8392 100644 --- a/paramiko/sftp_attr.py +++ b/paramiko/sftp_attr.py @@ -143,7 +143,7 @@ class SFTPAttributes (object): msg.add_int(long(self.st_mtime)) if self._flags & self.FLAG_EXTENDED: 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(val) return @@ -158,7 +158,7 @@ class SFTPAttributes (object): out += 'mode=' + oct(self.st_mode) + ' ' 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) - for k, v in self.attr.iteritems(): + for k, v in self.attr.items(): out += '"%s"=%r ' % (str(k), v) out += ']' return out diff --git a/paramiko/sftp_client.py b/paramiko/sftp_client.py index d921574..954cfa0 100644 --- a/paramiko/sftp_client.py +++ b/paramiko/sftp_client.py @@ -85,7 +85,7 @@ class SFTPClient (BaseSFTP): self.ultra_debug = transport.get_hexdump() try: server_version = self._send_version() - except EOFError, x: + except EOFError: raise SSHException('EOF during negotiation') self._log(INFO, 'Opened sftp connection (server version %d)' % server_version) @@ -178,7 +178,7 @@ class SFTPClient (BaseSFTP): while True: try: t, msg = self._request(CMD_READDIR, handle) - except EOFError, e: + except EOFError: # done with handle break if t != CMD_NAME: @@ -717,8 +717,8 @@ class SFTPClient (BaseSFTP): while True: try: t, data = self._read_packet() - except EOFError, e: - raise SSHException('Server connection dropped: %s' % (str(e),)) + except EOFError: + raise SSHException('Server connection dropped: %s' % str(sys.exc_info()[1])) msg = Message(data) num = msg.get_int() if num not in self._expecting: diff --git a/paramiko/sftp_file.py b/paramiko/sftp_file.py index 4ec936d..c0bc898 100644 --- a/paramiko/sftp_file.py +++ b/paramiko/sftp_file.py @@ -94,7 +94,7 @@ class SFTPFile (BufferedFile): k = [i for i in self._prefetch_reads if i[0] <= offset] if len(k) == 0: return False - k.sort(lambda x, y: cmp(x[0], y[0])) + k.sort(key=hash) buf_offset, buf_size = k[-1] if buf_offset + buf_size <= offset: # prefetch request ends before this one begins @@ -464,8 +464,8 @@ class SFTPFile (BufferedFile): # save exception and re-raise it on next file operation try: self.sftp._convert_status(msg) - except Exception, x: - self._saved_exception = x + except Exception: + self._saved_exception = sys.exc_info()[1] return if t != CMD_DATA: raise SFTPError('Expected data') diff --git a/paramiko/sftp_handle.py b/paramiko/sftp_handle.py index 29d3d0d..8b78063 100644 --- a/paramiko/sftp_handle.py +++ b/paramiko/sftp_handle.py @@ -100,7 +100,8 @@ class SFTPHandle (object): readfile.seek(offset) self.__tell = offset data = readfile.read(length) - except IOError, e: + except IOError: + e = sys.exc_info()[1] self.__tell = None return SFTPServer.convert_errno(e.errno) self.__tell += len(data) @@ -139,7 +140,8 @@ class SFTPHandle (object): self.__tell = offset writefile.write(data) writefile.flush() - except IOError, e: + except IOError: + e = sys.exc_info()[1] self.__tell = None return SFTPServer.convert_errno(e.errno) if self.__tell is not None: diff --git a/paramiko/sftp_server.py b/paramiko/sftp_server.py index 1833c2e..ec34008 100644 --- a/paramiko/sftp_server.py +++ b/paramiko/sftp_server.py @@ -92,7 +92,8 @@ class SFTPServer (BaseSFTP, SubsystemHandler): except EOFError: self._log(DEBUG, 'EOF -- end of session') return - except Exception, e: + except Exception: + e = sys.exc_info()[1] self._log(DEBUG, 'Exception on channel: ' + str(e)) self._log(DEBUG, util.tb_strings()) return @@ -100,7 +101,8 @@ class SFTPServer (BaseSFTP, SubsystemHandler): request_number = msg.get_int() try: 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, util.tb_strings()) # send some kind of failure message, at least @@ -113,9 +115,9 @@ class SFTPServer (BaseSFTP, SubsystemHandler): self.server.session_ended() super(SFTPServer, self).finish_subsystem() # 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() - for f in self.folder_table.itervalues(): + for f in self.folder_table.values(): f.close() self.file_table = {} self.folder_table = {} diff --git a/paramiko/transport.py b/paramiko/transport.py index c6ab127..c8a693e 100644 --- a/paramiko/transport.py +++ b/paramiko/transport.py @@ -177,7 +177,7 @@ class ChannelMap (object): def values(self): self._lock.acquire() try: - return self._map.values() + return list(self._map.values()) finally: self._lock.release() @@ -294,8 +294,8 @@ class Transport (threading.Thread): sock = socket.socket(af, socket.SOCK_STREAM) try: retry_on_signal(lambda: sock.connect((hostname, port))) - except socket.error, e: - reason = str(e) + except socket.error: + reason = str(sys.exc_info()[1]) else: break else: @@ -616,7 +616,7 @@ class Transport (threading.Thread): if not self.active: return self.stop_thread() - for chan in self._channels.values(): + for chan in list(self._channels.values()): chan._unlink() self.sock.close() @@ -691,7 +691,7 @@ class Transport (threading.Thread): """ 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"}. 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_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)) def open_channel(self, kind, dest_addr=None, src_addr=None): @@ -811,7 +813,9 @@ class Transport (threading.Thread): if port == 0: port = response.get_int() 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) handler = default_handler self._tcp_handler = handler @@ -845,22 +849,22 @@ class Transport (threading.Thread): """ 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 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 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. - @type bytes: int + @type byte_count: int """ m = Message() m.add_byte(chr(MSG_IGNORE)) - if bytes is None: - bytes = (ord(rng.read(1)) % 32) + 10 - m.add_bytes(rng.read(bytes)) + if byte_count is None: + byte_count = (byte_ord(rng.read(1)) % 32) + 10 + m.add_bytes(rng.read(byte_count)) self._send_user_message(m) def renegotiate_keys(self): @@ -1181,7 +1185,8 @@ class Transport (threading.Thread): return [] try: 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 not fallback or ('keyboard-interactive' not in x.allowed_types): raise @@ -1197,7 +1202,7 @@ class Transport (threading.Thread): return [] return [ password ] return self.auth_interactive(username, handler) - except SSHException, ignored: + except SSHException: # attempt failed; just raise the original exception raise x return None @@ -1513,7 +1518,7 @@ class Transport (threading.Thread): # only called if a channel has turned on x11 forwarding if handler is None: # 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._x11_handler = default_handler else: @@ -1604,22 +1609,26 @@ class Transport (threading.Thread): msg.add_byte(chr(MSG_UNIMPLEMENTED)) msg.add_int(m.seqno) self._send_message(msg) - except SSHException, e: + except SSHException: + e = sys.exc_info()[1] self._log(ERROR, 'Exception: ' + str(e)) self._log(ERROR, util.tb_strings()) self.saved_exception = e - except EOFError, e: + except EOFError: + e = sys.exc_info()[1] self._log(DEBUG, 'EOF in transport thread') #self._log(DEBUG, util.tb_strings()) self.saved_exception = e - except socket.error, e: + except socket.error: + e = sys.exc_info()[1] if type(e.args) is tuple: emsg = '%s (%d)' % (e.args[1], e.args[0]) else: emsg = e.args self._log(ERROR, 'Socket exception: ' + emsg) self.saved_exception = e - except Exception, e: + except Exception: + e = sys.exc_info()[1] self._log(ERROR, 'Unknown exception: ' + str(e)) self._log(ERROR, util.tb_strings()) self.saved_exception = e @@ -1679,7 +1688,8 @@ class Transport (threading.Thread): buf = self.packetizer.readline(timeout) except ProxyCommandFailure: raise - except Exception, x: + except Exception: + x = sys.exc_info()[1] raise SSHException('Error reading SSH protocol banner' + str(x)) if buf[:4] == 'SSH-': break @@ -1690,7 +1700,7 @@ class Transport (threading.Thread): self.remote_version = buf # pull off any attached comment comment = '' - i = string.find(buf, ' ') + i = buf.find(' ') if i >= 0: comment = buf[i+1:] 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 client, we pick the first item in our list that the server supports. 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: - 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: raise SSHException('Incompatible ssh peer (no acceptable kex algorithm)') self.kex_engine = self._kex_info[agreed_kex[0]](self) if self.server_mode: - available_server_keys = filter(self.server_key_dict.keys().__contains__, - self._preferred_keys) - agreed_keys = filter(available_server_keys.__contains__, server_key_algo_list) + available_server_keys = list(filter(list(self.server_key_dict.keys()).__contains__, + self._preferred_keys)) + agreed_keys = list(filter(available_server_keys.__contains__, server_key_algo_list)) 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: raise SSHException('Incompatible ssh peer (no acceptable host key)') 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)') if self.server_mode: - agreed_local_ciphers = filter(self._preferred_ciphers.__contains__, - server_encrypt_algo_list) - agreed_remote_ciphers = filter(self._preferred_ciphers.__contains__, - client_encrypt_algo_list) + agreed_local_ciphers = list(filter(self._preferred_ciphers.__contains__, + server_encrypt_algo_list)) + agreed_remote_ciphers = list(filter(self._preferred_ciphers.__contains__, + client_encrypt_algo_list)) else: - agreed_local_ciphers = filter(client_encrypt_algo_list.__contains__, - self._preferred_ciphers) - agreed_remote_ciphers = filter(server_encrypt_algo_list.__contains__, - self._preferred_ciphers) + agreed_local_ciphers = list(filter(client_encrypt_algo_list.__contains__, + self._preferred_ciphers)) + agreed_remote_ciphers = list(filter(server_encrypt_algo_list.__contains__, + self._preferred_ciphers)) if (len(agreed_local_ciphers) == 0) or (len(agreed_remote_ciphers) == 0): raise SSHException('Incompatible ssh server (no acceptable ciphers)') 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)) if self.server_mode: - agreed_remote_macs = filter(self._preferred_macs.__contains__, client_mac_algo_list) - agreed_local_macs = filter(self._preferred_macs.__contains__, server_mac_algo_list) + agreed_remote_macs = list(filter(self._preferred_macs.__contains__, client_mac_algo_list)) + agreed_local_macs = list(filter(self._preferred_macs.__contains__, server_mac_algo_list)) else: - agreed_local_macs = filter(client_mac_algo_list.__contains__, self._preferred_macs) - agreed_remote_macs = filter(server_mac_algo_list.__contains__, self._preferred_macs) + agreed_local_macs = list(filter(client_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): raise SSHException('Incompatible ssh server (no acceptable macs)') self.local_mac = agreed_local_macs[0] self.remote_mac = agreed_remote_macs[0] if self.server_mode: - agreed_remote_compression = filter(self._preferred_compression.__contains__, client_compress_algo_list) - agreed_local_compression = filter(self._preferred_compression.__contains__, server_compress_algo_list) + agreed_remote_compression = list(filter(self._preferred_compression.__contains__, client_compress_algo_list)) + agreed_local_compression = list(filter(self._preferred_compression.__contains__, server_compress_algo_list)) else: - agreed_local_compression = filter(client_compress_algo_list.__contains__, self._preferred_compression) - agreed_remote_compression = filter(server_compress_algo_list.__contains__, self._preferred_compression) + agreed_local_compression = list(filter(client_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): 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] diff --git a/paramiko/util.py b/paramiko/util.py index 85ee6b0..299f44a 100644 --- a/paramiko/util.py +++ b/paramiko/util.py @@ -276,13 +276,14 @@ def retry_on_signal(function): while True: try: return function() - except EnvironmentError, e: + except EnvironmentError: + e = sys.exc_info()[1] if e.errno != errno.EINTR: raise class Counter (object): """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.overflow = overflow # start with value - 1 so we don't have to store intermediate values when counting diff --git a/tests/stub_sftp.py b/tests/stub_sftp.py index e5f4454..b8bea9b 100644 --- a/tests/stub_sftp.py +++ b/tests/stub_sftp.py @@ -40,7 +40,8 @@ class StubSFTPHandle (SFTPHandle): def stat(self): try: 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) def chattr(self, attr): @@ -49,7 +50,8 @@ class StubSFTPHandle (SFTPHandle): try: SFTPServer.set_file_attr(self.filename, attr) return SFTP_OK - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) @@ -71,21 +73,24 @@ class StubSFTPServer (SFTPServerInterface): attr.filename = fname out.append(attr) return out - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) def stat(self, path): path = self._realpath(path) try: return SFTPAttributes.from_stat(os.stat(path)) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) def lstat(self, path): path = self._realpath(path) try: return SFTPAttributes.from_stat(os.lstat(path)) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) def open(self, path, flags, attr): @@ -100,7 +105,8 @@ class StubSFTPServer (SFTPServerInterface): # os.open() defaults to 0777 which is # an odd default mode for files fd = os.open(path, flags, 0666) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) if (flags & os.O_CREAT) and (attr is not None): attr._flags &= ~attr.FLAG_PERMISSIONS @@ -120,7 +126,8 @@ class StubSFTPServer (SFTPServerInterface): fstr = 'rb' try: f = os.fdopen(fd, fstr) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) fobj = StubSFTPHandle(flags) fobj.filename = path @@ -132,7 +139,8 @@ class StubSFTPServer (SFTPServerInterface): path = self._realpath(path) try: os.remove(path) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) return SFTP_OK @@ -141,7 +149,8 @@ class StubSFTPServer (SFTPServerInterface): newpath = self._realpath(newpath) try: os.rename(oldpath, newpath) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) return SFTP_OK @@ -151,7 +160,8 @@ class StubSFTPServer (SFTPServerInterface): os.mkdir(path) if attr is not None: SFTPServer.set_file_attr(path, attr) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) return SFTP_OK @@ -159,7 +169,8 @@ class StubSFTPServer (SFTPServerInterface): path = self._realpath(path) try: os.rmdir(path) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) return SFTP_OK @@ -167,7 +178,8 @@ class StubSFTPServer (SFTPServerInterface): path = self._realpath(path) try: SFTPServer.set_file_attr(path, attr) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) return SFTP_OK @@ -187,7 +199,8 @@ class StubSFTPServer (SFTPServerInterface): target_path = '' try: os.symlink(target_path, path) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) return SFTP_OK @@ -195,7 +208,8 @@ class StubSFTPServer (SFTPServerInterface): path = self._realpath(path) try: symlink = os.readlink(path) - except OSError, e: + except OSError: + e = sys.exc_info()[1] return SFTPServer.convert_errno(e.errno) # if it's absolute, remove the root if os.path.isabs(symlink): diff --git a/tests/test_transport.py b/tests/test_transport.py index ccd3f0c..d8cd10d 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -249,7 +249,7 @@ class TransportTest(ParamikoTest): try: chan.exec_command('no') self.assert_(False) - except SSHException, x: + except SSHException: pass chan = self.tc.open_session() @@ -302,7 +302,8 @@ class TransportTest(ParamikoTest): try: chan = self.tc.open_channel('bogus') self.fail('expected exception') - except ChannelException, x: + except ChannelException: + x = sys.exc_info()[1] self.assert_(x.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED) def test_9_exit_status(self): @@ -444,7 +445,8 @@ class TransportTest(ParamikoTest): schan = self.ts.accept(1.0) requested = [] - def handler(c, (addr, port)): + def handler(c, addr_port): + addr, port = addr_port requested.append((addr, port)) self.tc._queue_incoming_channel(c) @@ -479,9 +481,9 @@ class TransportTest(ParamikoTest): schan = self.ts.accept(1.0) requested = [] - def handler(c, (origin_addr, origin_port), (server_addr, server_port)): - requested.append((origin_addr, origin_port)) - requested.append((server_addr, server_port)) + def handler(c, origin_addr_port, server_addr_port): + requested.append(origin_addr_port) + requested.append(server_addr_port) self.tc._queue_incoming_channel(c) port = self.tc.request_port_forward('127.0.0.1', 0, handler) diff --git a/tests/test_util.py b/tests/test_util.py index 12575f8..7e656df 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -65,7 +65,7 @@ class UtilTest(ParamikoTest): """ verify that all the classes can be imported from paramiko. """ - symbols = globals().keys() + symbols = list(globals().keys()) self.assertTrue('Transport' in symbols) self.assertTrue('SSHClient' in symbols) self.assertTrue('MissingHostKeyPolicy' in symbols) @@ -148,8 +148,8 @@ class UtilTest(ParamikoTest): try: hostdict = paramiko.util.load_host_keys('hostfile.temp') self.assertEquals(2, len(hostdict)) - self.assertEquals(1, len(hostdict.values()[0])) - self.assertEquals(1, len(hostdict.values()[1])) + self.assertEquals(1, len(list(hostdict.values())[0])) + self.assertEquals(1, len(list(hostdict.values())[1])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() self.assertEquals('E6684DB30E109B67B70FF1DC5C7F1363', fp) finally: