[Python 3]: Migrated to print functions.

This commit is contained in:
Dorian 2013-08-13 15:40:57 -04:00
parent e06b0f597e
commit 0847ac780b
8 changed files with 69 additions and 57 deletions

View File

@ -18,6 +18,7 @@
# along with Paramiko; if not, write to the Free Software Foundation, Inc., # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
from __future__ import print_function
import base64 import base64
from binascii import hexlify from binascii import hexlify
@ -45,13 +46,13 @@ def agent_auth(transport, username):
return return
for key in agent_keys: for key in agent_keys:
print 'Trying ssh-agent key %s' % hexlify(key.get_fingerprint()), print('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()), end=' ')
try: try:
transport.auth_publickey(username, key) transport.auth_publickey(username, key)
print '... success!' print('... success!')
return return
except paramiko.SSHException: except paramiko.SSHException:
print '... nope.' print('... nope.')
def manual_auth(username, hostname): def manual_auth(username, hostname):
@ -98,7 +99,7 @@ if len(sys.argv) > 1:
else: else:
hostname = raw_input('Hostname: ') hostname = raw_input('Hostname: ')
if len(hostname) == 0: if len(hostname) == 0:
print '*** Hostname required.' print('*** Hostname required.')
sys.exit(1) sys.exit(1)
port = 22 port = 22
if hostname.find(':') >= 0: if hostname.find(':') >= 0:
@ -110,7 +111,7 @@ try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, port)) sock.connect((hostname, port))
except Exception, e: except Exception, e:
print '*** Connect failed: ' + str(e) print('*** Connect failed: ' + str(e))
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
@ -119,7 +120,7 @@ try:
try: try:
t.start_client() t.start_client()
except paramiko.SSHException: except paramiko.SSHException:
print '*** SSH negotiation failed.' print('*** SSH negotiation failed.')
sys.exit(1) sys.exit(1)
try: try:
@ -128,20 +129,20 @@ try:
try: try:
keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
except IOError: except IOError:
print '*** Unable to open host keys file' print('*** Unable to open host keys file')
keys = {} keys = {}
# check server's host key -- this is important. # check server's host key -- this is important.
key = t.get_remote_server_key() key = t.get_remote_server_key()
if not keys.has_key(hostname): if not keys.has_key(hostname):
print '*** WARNING: Unknown host key!' print('*** WARNING: Unknown host key!')
elif not keys[hostname].has_key(key.get_name()): elif not keys[hostname].has_key(key.get_name()):
print '*** WARNING: Unknown host key!' print('*** WARNING: Unknown host key!')
elif keys[hostname][key.get_name()] != key: elif keys[hostname][key.get_name()] != key:
print '*** WARNING: Host key has changed!!!' print('*** WARNING: Host key has changed!!!')
sys.exit(1) sys.exit(1)
else: else:
print '*** Host key OK.' print('*** Host key OK.')
# get username # get username
if username == '': if username == '':
@ -154,21 +155,21 @@ try:
if not t.is_authenticated(): if not t.is_authenticated():
manual_auth(username, hostname) manual_auth(username, hostname)
if not t.is_authenticated(): if not t.is_authenticated():
print '*** Authentication failed. :(' print('*** Authentication failed. :(')
t.close() t.close()
sys.exit(1) sys.exit(1)
chan = t.open_session() chan = t.open_session()
chan.get_pty() chan.get_pty()
chan.invoke_shell() chan.invoke_shell()
print '*** Here we go!' print('*** Here we go!')
print print()
interactive.interactive_shell(chan) interactive.interactive_shell(chan)
chan.close() chan.close()
t.close() t.close()
except Exception, e: except Exception, e:
print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
traceback.print_exc() traceback.print_exc()
try: try:
t.close() t.close()

View File

@ -17,7 +17,8 @@
# You should have received a copy of the GNU Lesser General Public License # You should have received a copy of the GNU Lesser General Public License
# along with Paramiko; if not, write to the Free Software Foundation, Inc., # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
from __future__ import with_statement
from __future__ import print_function, with_statement
import string import string
import sys import sys
@ -47,16 +48,16 @@ key_dispatch_table = {
def progress(arg=None): def progress(arg=None):
if not arg: if not arg:
print '0%\x08\x08\x08', print('0%\x08\x08\x08', end=' ')
sys.stdout.flush() sys.stdout.flush()
elif arg[0] == 'p': elif arg[0] == 'p':
print '25%\x08\x08\x08\x08', print('25%\x08\x08\x08\x08', end=' ')
sys.stdout.flush() sys.stdout.flush()
elif arg[0] == 'h': elif arg[0] == 'h':
print '50%\x08\x08\x08\x08', print('50%\x08\x08\x08\x08', end=' ')
sys.stdout.flush() sys.stdout.flush()
elif arg[0] == 'x': elif arg[0] == 'x':
print '75%\x08\x08\x08\x08', print('75%\x08\x08\x08\x08', end=' ')
sys.stdout.flush() sys.stdout.flush()
if __name__ == '__main__': if __name__ == '__main__':
@ -121,7 +122,7 @@ if __name__ == '__main__':
f.write(" %s" % comment) f.write(" %s" % comment)
if options.verbose: if options.verbose:
print "done." print("done.")
hash = hexlify(pub.get_fingerprint()) hash = hexlify(pub.get_fingerprint())
print "Fingerprint: %d %s %s.pub (%s)" % (bits, ":".join([ hash[i:2+i] for i in range(0, len(hash), 2)]), filename, string.upper(ktype)) print("Fingerprint: %d %s %s.pub (%s)" % (bits, ":".join([ hash[i:2 + i] for i in range(0, len(hash), 2)]), filename, string.upper(ktype)))

View File

@ -18,6 +18,8 @@
# along with Paramiko; if not, write to the Free Software Foundation, Inc., # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
from __future__ import print_function
import base64 import base64
from binascii import hexlify from binascii import hexlify
import os import os
@ -35,7 +37,7 @@ paramiko.util.log_to_file('demo_server.log')
host_key = paramiko.RSAKey(filename='test_rsa.key') host_key = paramiko.RSAKey(filename='test_rsa.key')
#host_key = paramiko.DSSKey(filename='test_dss.key') #host_key = paramiko.DSSKey(filename='test_dss.key')
print 'Read key: ' + hexlify(host_key.get_fingerprint()) print('Read key: ' + hexlify(host_key.get_fingerprint()))
class Server (paramiko.ServerInterface): class Server (paramiko.ServerInterface):
@ -61,7 +63,7 @@ class Server (paramiko.ServerInterface):
return paramiko.AUTH_FAILED return paramiko.AUTH_FAILED
def check_auth_publickey(self, username, key): def check_auth_publickey(self, username, key):
print 'Auth attempt with key: ' + hexlify(key.get_fingerprint()) print('Auth attempt with key: ' + hexlify(key.get_fingerprint()))
if (username == 'robey') and (key == self.good_pub_key): if (username == 'robey') and (key == self.good_pub_key):
return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED return paramiko.AUTH_FAILED
@ -84,46 +86,46 @@ try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 2200)) sock.bind(('', 2200))
except Exception, e: except Exception, e:
print '*** Bind failed: ' + str(e) print('*** Bind failed: ' + str(e))
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
try: try:
sock.listen(100) sock.listen(100)
print 'Listening for connection ...' print('Listening for connection ...')
client, addr = sock.accept() client, addr = sock.accept()
except Exception, e: except Exception, e:
print '*** Listen/accept failed: ' + str(e) print('*** Listen/accept failed: ' + str(e))
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
print 'Got a connection!' print('Got a connection!')
try: try:
t = paramiko.Transport(client) t = paramiko.Transport(client)
try: try:
t.load_server_moduli() t.load_server_moduli()
except: except:
print '(Failed to load moduli -- gex will be unsupported.)' print('(Failed to load moduli -- gex will be unsupported.)')
raise raise
t.add_server_key(host_key) t.add_server_key(host_key)
server = Server() server = Server()
try: try:
t.start_server(server=server) t.start_server(server=server)
except paramiko.SSHException, x: except paramiko.SSHException, x:
print '*** SSH negotiation failed.' print('*** SSH negotiation failed.')
sys.exit(1) sys.exit(1)
# wait for auth # wait for auth
chan = t.accept(20) chan = t.accept(20)
if chan is None: if chan is None:
print '*** No channel.' print('*** No channel.')
sys.exit(1) sys.exit(1)
print 'Authenticated!' print('Authenticated!')
server.event.wait(10) server.event.wait(10)
if not server.event.isSet(): if not server.event.isSet():
print '*** Client never asked for a shell.' print('*** Client never asked for a shell.')
sys.exit(1) sys.exit(1)
chan.send('\r\n\r\nWelcome to my dorky little BBS!\r\n\r\n') chan.send('\r\n\r\nWelcome to my dorky little BBS!\r\n\r\n')
@ -136,7 +138,7 @@ try:
chan.close() chan.close()
except Exception, e: except Exception, e:
print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
traceback.print_exc() traceback.print_exc()
try: try:
t.close() t.close()

View File

@ -20,6 +20,8 @@
# based on code provided by raymond mosteller (thanks!) # based on code provided by raymond mosteller (thanks!)
from __future__ import print_function
import base64 import base64
import getpass import getpass
import os import os
@ -42,7 +44,7 @@ if len(sys.argv) > 1:
else: else:
hostname = raw_input('Hostname: ') hostname = raw_input('Hostname: ')
if len(hostname) == 0: if len(hostname) == 0:
print '*** Hostname required.' print('*** Hostname required.')
sys.exit(1) sys.exit(1)
port = 22 port = 22
if hostname.find(':') >= 0: if hostname.find(':') >= 0:
@ -69,13 +71,13 @@ except IOError:
# try ~/ssh/ too, because windows can't have a folder named ~/.ssh/ # try ~/ssh/ too, because windows can't have a folder named ~/.ssh/
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
except IOError: except IOError:
print '*** Unable to open host keys file' print('*** Unable to open host keys file')
host_keys = {} host_keys = {}
if host_keys.has_key(hostname): if host_keys.has_key(hostname):
hostkeytype = host_keys[hostname].keys()[0] hostkeytype = host_keys[hostname].keys()[0]
hostkey = host_keys[hostname][hostkeytype] hostkey = host_keys[hostname][hostkeytype]
print 'Using host key of type %s' % hostkeytype print('Using host key of type %s' % hostkeytype)
# now, connect and use paramiko Transport to negotiate SSH2 across the connection # now, connect and use paramiko Transport to negotiate SSH2 across the connection
@ -86,22 +88,22 @@ try:
# dirlist on remote host # dirlist on remote host
dirlist = sftp.listdir('.') dirlist = sftp.listdir('.')
print "Dirlist:", dirlist print("Dirlist:", dirlist)
# copy this demo onto the server # copy this demo onto the server
try: try:
sftp.mkdir("demo_sftp_folder") sftp.mkdir("demo_sftp_folder")
except IOError: except IOError:
print '(assuming demo_sftp_folder/ already exists)' print('(assuming demo_sftp_folder/ already exists)')
sftp.open('demo_sftp_folder/README', 'w').write('This was created by demo_sftp.py.\n') sftp.open('demo_sftp_folder/README', 'w').write('This was created by demo_sftp.py.\n')
data = open('demo_sftp.py', 'r').read() data = open('demo_sftp.py', 'r').read()
sftp.open('demo_sftp_folder/demo_sftp.py', 'w').write(data) sftp.open('demo_sftp_folder/demo_sftp.py', 'w').write(data)
print 'created demo_sftp_folder/ on the server' print('created demo_sftp_folder/ on the server')
# copy the README back here # copy the README back here
data = sftp.open('demo_sftp_folder/README', 'r').read() data = sftp.open('demo_sftp_folder/README', 'r').read()
open('README_demo_sftp', 'w').write(data) open('README_demo_sftp', 'w').write(data)
print 'copied README back here' print('copied README back here')
# BETTER: use the get() and put() methods # BETTER: use the get() and put() methods
sftp.put('demo_sftp.py', 'demo_sftp_folder/demo_sftp.py') sftp.put('demo_sftp.py', 'demo_sftp_folder/demo_sftp.py')
@ -110,7 +112,7 @@ try:
t.close() t.close()
except Exception, e: except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e) print('*** Caught exception: %s: %s' % (e.__class__, e))
traceback.print_exc() traceback.print_exc()
try: try:
t.close() t.close()

View File

@ -18,6 +18,7 @@
# along with Paramiko; if not, write to the Free Software Foundation, Inc., # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
from __future__ import print_function
import base64 import base64
import getpass import getpass
@ -42,7 +43,7 @@ if len(sys.argv) > 1:
else: else:
hostname = raw_input('Hostname: ') hostname = raw_input('Hostname: ')
if len(hostname) == 0: if len(hostname) == 0:
print '*** Hostname required.' print('*** Hostname required.')
sys.exit(1) sys.exit(1)
port = 22 port = 22
if hostname.find(':') >= 0: if hostname.find(':') >= 0:
@ -64,18 +65,18 @@ try:
client = paramiko.SSHClient() client = paramiko.SSHClient()
client.load_system_host_keys() client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy) client.set_missing_host_key_policy(paramiko.WarningPolicy)
print '*** Connecting...' print('*** Connecting...')
client.connect(hostname, port, username, password) client.connect(hostname, port, username, password)
chan = client.invoke_shell() chan = client.invoke_shell()
print repr(client.get_transport()) print(repr(client.get_transport()))
print '*** Here we go!' print('*** Here we go!')
print print()
interactive.interactive_shell(chan) interactive.interactive_shell(chan)
chan.close() chan.close()
client.close() client.close()
except Exception, e: except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e) print('*** Caught exception: %s: %s' % (e.__class__, e))
traceback.print_exc() traceback.print_exc()
try: try:
client.close() client.close()

View File

@ -26,6 +26,8 @@ forwarding (the openssh -L option) from a local port through a tunneled
connection to a destination reachable from the SSH server machine. connection to a destination reachable from the SSH server machine.
""" """
from __future__ import print_function
import getpass import getpass
import os import os
import socket import socket
@ -96,7 +98,7 @@ def forward_tunnel(local_port, remote_host, remote_port, transport):
def verbose(s): def verbose(s):
if g_verbose: if g_verbose:
print s print(s)
HELP = """\ HELP = """\
@ -164,7 +166,7 @@ def main():
client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile, client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile,
look_for_keys=options.look_for_keys, password=password) look_for_keys=options.look_for_keys, password=password)
except Exception, e: except Exception, e:
print '*** Failed to connect to %s:%d: %r' % (server[0], server[1], e) print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e))
sys.exit(1) sys.exit(1)
verbose('Now forwarding port %d to %s:%d ...' % (options.port, remote[0], remote[1])) verbose('Now forwarding port %d to %s:%d ...' % (options.port, remote[0], remote[1]))
@ -172,7 +174,7 @@ def main():
try: try:
forward_tunnel(options.port, remote[0], remote[1], client.get_transport()) forward_tunnel(options.port, remote[0], remote[1], client.get_transport())
except KeyboardInterrupt: except KeyboardInterrupt:
print 'C-c: Port forwarding stopped.' print('C-c: Port forwarding stopped.')
sys.exit(0) sys.exit(0)

View File

@ -16,6 +16,7 @@
# along with Paramiko; if not, write to the Free Software Foundation, Inc., # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
from __future__ import print_function
import socket import socket
import sys import sys
@ -51,7 +52,7 @@ def posix_shell(chan):
try: try:
x = chan.recv(1024) x = chan.recv(1024)
if len(x) == 0: if len(x) == 0:
print '\r\n*** EOF\r\n', print('\r\n*** EOF\r\n', end=' ')
break break
sys.stdout.write(x) sys.stdout.write(x)
sys.stdout.flush() sys.stdout.flush()

View File

@ -26,6 +26,8 @@ forwarding (the openssh -R option) from a remote port through a tunneled
connection to a destination reachable from the local machine. connection to a destination reachable from the local machine.
""" """
from __future__ import print_function
import getpass import getpass
import os import os
import socket import socket
@ -82,7 +84,7 @@ def reverse_forward_tunnel(server_port, remote_host, remote_port, transport):
def verbose(s): def verbose(s):
if g_verbose: if g_verbose:
print s print(s)
HELP = """\ HELP = """\
@ -151,7 +153,7 @@ def main():
client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile, client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile,
look_for_keys=options.look_for_keys, password=password) look_for_keys=options.look_for_keys, password=password)
except Exception, e: except Exception, e:
print '*** Failed to connect to %s:%d: %r' % (server[0], server[1], e) print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e))
sys.exit(1) sys.exit(1)
verbose('Now forwarding remote port %d to %s:%d ...' % (options.port, remote[0], remote[1])) verbose('Now forwarding remote port %d to %s:%d ...' % (options.port, remote[0], remote[1]))
@ -159,7 +161,7 @@ def main():
try: try:
reverse_forward_tunnel(options.port, remote[0], remote[1], client.get_transport()) reverse_forward_tunnel(options.port, remote[0], remote[1], client.get_transport())
except KeyboardInterrupt: except KeyboardInterrupt:
print 'C-c: Port forwarding stopped.' print('C-c: Port forwarding stopped.')
sys.exit(0) sys.exit(0)