summaryrefslogtreecommitdiff
path: root/demos
diff options
context:
space:
mode:
Diffstat (limited to 'demos')
-rwxr-xr-xdemos/demo.py53
-rwxr-xr-xdemos/demo_keygen.py23
-rw-r--r--demos/demo_server.py43
-rwxr-xr-xdemos/demo_sftp.py37
-rwxr-xr-xdemos/demo_simple.py23
-rw-r--r--demos/forward.py16
-rw-r--r--demos/interactive.py5
-rwxr-xr-xdemos/rforward.py10
8 files changed, 113 insertions, 97 deletions
diff --git a/demos/demo.py b/demos/demo.py
index aa4bdaa..fff6178 100755
--- a/demos/demo.py
+++ b/demos/demo.py
@@ -28,9 +28,13 @@ import socket
import sys
import time
import traceback
+from paramiko.py3compat import input
import paramiko
-import interactive
+try:
+ import interactive
+except ImportError:
+ from . import interactive
def agent_auth(transport, username):
@@ -45,24 +49,24 @@ def agent_auth(transport, username):
return
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()))
try:
transport.auth_publickey(username, key)
- print '... success!'
+ print('... success!')
return
except paramiko.SSHException:
- print '... nope.'
+ print('... nope.')
def manual_auth(username, hostname):
default_auth = 'p'
- auth = raw_input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
+ auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
if len(auth) == 0:
auth = default_auth
if auth == 'r':
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
- path = raw_input('RSA key [%s]: ' % default_path)
+ path = input('RSA key [%s]: ' % default_path)
if len(path) == 0:
path = default_path
try:
@@ -73,7 +77,7 @@ def manual_auth(username, hostname):
t.auth_publickey(username, key)
elif auth == 'd':
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
- path = raw_input('DSS key [%s]: ' % default_path)
+ path = input('DSS key [%s]: ' % default_path)
if len(path) == 0:
path = default_path
try:
@@ -96,9 +100,9 @@ if len(sys.argv) > 1:
if hostname.find('@') >= 0:
username, hostname = hostname.split('@')
else:
- hostname = raw_input('Hostname: ')
+ hostname = input('Hostname: ')
if len(hostname) == 0:
- print '*** Hostname required.'
+ print('*** Hostname required.')
sys.exit(1)
port = 22
if hostname.find(':') >= 0:
@@ -109,8 +113,8 @@ if hostname.find(':') >= 0:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, port))
-except Exception, e:
- print '*** Connect failed: ' + str(e)
+except Exception as e:
+ print('*** Connect failed: ' + str(e))
traceback.print_exc()
sys.exit(1)
@@ -119,7 +123,7 @@ try:
try:
t.start_client()
except paramiko.SSHException:
- print '*** SSH negotiation failed.'
+ print('*** SSH negotiation failed.')
sys.exit(1)
try:
@@ -128,25 +132,25 @@ try:
try:
keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
except IOError:
- print '*** Unable to open host keys file'
+ print('*** Unable to open host keys file')
keys = {}
# check server's host key -- this is important.
key = t.get_remote_server_key()
- if not keys.has_key(hostname):
- print '*** WARNING: Unknown host key!'
- elif not keys[hostname].has_key(key.get_name()):
- print '*** WARNING: Unknown host key!'
+ if hostname not in keys:
+ print('*** WARNING: Unknown host key!')
+ elif key.get_name() not in keys[hostname]:
+ print('*** WARNING: Unknown host key!')
elif keys[hostname][key.get_name()] != key:
- print '*** WARNING: Host key has changed!!!'
+ print('*** WARNING: Host key has changed!!!')
sys.exit(1)
else:
- print '*** Host key OK.'
+ print('*** Host key OK.')
# get username
if username == '':
default_username = getpass.getuser()
- username = raw_input('Username [%s]: ' % default_username)
+ username = input('Username [%s]: ' % default_username)
if len(username) == 0:
username = default_username
@@ -154,21 +158,20 @@ try:
if not t.is_authenticated():
manual_auth(username, hostname)
if not t.is_authenticated():
- print '*** Authentication failed. :('
+ print('*** Authentication failed. :(')
t.close()
sys.exit(1)
chan = t.open_session()
chan.get_pty()
chan.invoke_shell()
- print '*** Here we go!'
- print
+ print('*** Here we go!\n')
interactive.interactive_shell(chan)
chan.close()
t.close()
-except Exception, e:
- print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e)
+except Exception as e:
+ print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
traceback.print_exc()
try:
t.close()
diff --git a/demos/demo_keygen.py b/demos/demo_keygen.py
index bdd7388..860ee4e 100755
--- a/demos/demo_keygen.py
+++ b/demos/demo_keygen.py
@@ -17,9 +17,7 @@
# 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.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
-from __future__ import with_statement
-import string
import sys
from binascii import hexlify
@@ -28,6 +26,7 @@ from optparse import OptionParser
from paramiko import DSSKey
from paramiko import RSAKey
from paramiko.ssh_exception import SSHException
+from paramiko.py3compat import u
usage="""
%prog [-v] [-b bits] -t type [-N new_passphrase] [-f output_keyfile]"""
@@ -47,16 +46,16 @@ key_dispatch_table = {
def progress(arg=None):
if not arg:
- print '0%\x08\x08\x08',
+ sys.stdout.write('0%\x08\x08\x08 ')
sys.stdout.flush()
elif arg[0] == 'p':
- print '25%\x08\x08\x08\x08',
+ sys.stdout.write('25%\x08\x08\x08\x08 ')
sys.stdout.flush()
elif arg[0] == 'h':
- print '50%\x08\x08\x08\x08',
+ sys.stdout.write('50%\x08\x08\x08\x08 ')
sys.stdout.flush()
elif arg[0] == 'x':
- print '75%\x08\x08\x08\x08',
+ sys.stdout.write('75%\x08\x08\x08\x08 ')
sys.stdout.flush()
if __name__ == '__main__':
@@ -92,8 +91,8 @@ if __name__ == '__main__':
parser.print_help()
sys.exit(0)
- for o in default_values.keys():
- globals()[o] = getattr(options, o, default_values[string.lower(o)])
+ for o in list(default_values.keys()):
+ globals()[o] = getattr(options, o, default_values[o.lower()])
if options.newphrase:
phrase = getattr(options, 'newphrase')
@@ -106,7 +105,7 @@ if __name__ == '__main__':
if ktype == 'dsa' and bits > 1024:
raise SSHException("DSA Keys must be 1024 bits")
- if not key_dispatch_table.has_key(ktype):
+ if ktype not in key_dispatch_table:
raise SSHException("Unknown %s algorithm to generate keys pair" % ktype)
# generating private key
@@ -121,7 +120,7 @@ if __name__ == '__main__':
f.write(" %s" % comment)
if options.verbose:
- print "done."
+ print("done.")
- 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))
+ hash = u(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, ktype.upper()))
diff --git a/demos/demo_server.py b/demos/demo_server.py
index 915b0c6..bb35258 100644
--- a/demos/demo_server.py
+++ b/demos/demo_server.py
@@ -27,6 +27,7 @@ import threading
import traceback
import paramiko
+from paramiko.py3compat import b, u, decodebytes
# setup logging
@@ -35,17 +36,17 @@ paramiko.util.log_to_file('demo_server.log')
host_key = paramiko.RSAKey(filename='test_rsa.key')
#host_key = paramiko.DSSKey(filename='test_dss.key')
-print 'Read key: ' + hexlify(host_key.get_fingerprint())
+print('Read key: ' + u(hexlify(host_key.get_fingerprint())))
class Server (paramiko.ServerInterface):
# 'data' is the output of base64.encodestring(str(key))
# (using the "user_rsa_key" files)
- data = 'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp' + \
- 'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC' + \
- 'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT' + \
- 'UWT10hcuO4Ks8='
- good_pub_key = paramiko.RSAKey(data=base64.decodestring(data))
+ data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
+ b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
+ b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
+ b'UWT10hcuO4Ks8=')
+ good_pub_key = paramiko.RSAKey(data=decodebytes(data))
def __init__(self):
self.event = threading.Event()
@@ -61,7 +62,7 @@ class Server (paramiko.ServerInterface):
return paramiko.AUTH_FAILED
def check_auth_publickey(self, username, key):
- print 'Auth attempt with key: ' + hexlify(key.get_fingerprint())
+ print('Auth attempt with key: ' + u(hexlify(key.get_fingerprint())))
if (username == 'robey') and (key == self.good_pub_key):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
@@ -83,47 +84,47 @@ try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 2200))
-except Exception, e:
- print '*** Bind failed: ' + str(e)
+except Exception as e:
+ print('*** Bind failed: ' + str(e))
traceback.print_exc()
sys.exit(1)
try:
sock.listen(100)
- print 'Listening for connection ...'
+ print('Listening for connection ...')
client, addr = sock.accept()
-except Exception, e:
- print '*** Listen/accept failed: ' + str(e)
+except Exception as e:
+ print('*** Listen/accept failed: ' + str(e))
traceback.print_exc()
sys.exit(1)
-print 'Got a connection!'
+print('Got a connection!')
try:
t = paramiko.Transport(client)
try:
t.load_server_moduli()
except:
- print '(Failed to load moduli -- gex will be unsupported.)'
+ print('(Failed to load moduli -- gex will be unsupported.)')
raise
t.add_server_key(host_key)
server = Server()
try:
t.start_server(server=server)
- except paramiko.SSHException, x:
- print '*** SSH negotiation failed.'
+ except paramiko.SSHException:
+ print('*** SSH negotiation failed.')
sys.exit(1)
# wait for auth
chan = t.accept(20)
if chan is None:
- print '*** No channel.'
+ print('*** No channel.')
sys.exit(1)
- print 'Authenticated!'
+ print('Authenticated!')
server.event.wait(10)
if not server.event.isSet():
- print '*** Client never asked for a shell.'
+ print('*** Client never asked for a shell.')
sys.exit(1)
chan.send('\r\n\r\nWelcome to my dorky little BBS!\r\n\r\n')
@@ -135,8 +136,8 @@ try:
chan.send('\r\nI don\'t like you, ' + username + '.\r\n')
chan.close()
-except Exception, e:
- print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e)
+except Exception as e:
+ print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
traceback.print_exc()
try:
t.close()
diff --git a/demos/demo_sftp.py b/demos/demo_sftp.py
index 7c4aaba..a34f2b1 100755
--- a/demos/demo_sftp.py
+++ b/demos/demo_sftp.py
@@ -28,6 +28,7 @@ import sys
import traceback
import paramiko
+from paramiko.py3compat import input
# setup logging
@@ -40,9 +41,9 @@ if len(sys.argv) > 1:
if hostname.find('@') >= 0:
username, hostname = hostname.split('@')
else:
- hostname = raw_input('Hostname: ')
+ hostname = input('Hostname: ')
if len(hostname) == 0:
- print '*** Hostname required.'
+ print('*** Hostname required.')
sys.exit(1)
port = 22
if hostname.find(':') >= 0:
@@ -53,7 +54,7 @@ if hostname.find(':') >= 0:
# get username
if username == '':
default_username = getpass.getuser()
- username = raw_input('Username [%s]: ' % default_username)
+ username = input('Username [%s]: ' % default_username)
if len(username) == 0:
username = default_username
password = getpass.getpass('Password for %s@%s: ' % (username, hostname))
@@ -69,13 +70,13 @@ except IOError:
# 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'))
except IOError:
- print '*** Unable to open host keys file'
+ print('*** Unable to open host keys file')
host_keys = {}
-if host_keys.has_key(hostname):
+if hostname in host_keys:
hostkeytype = host_keys[hostname].keys()[0]
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
@@ -86,22 +87,26 @@ try:
# dirlist on remote host
dirlist = sftp.listdir('.')
- print "Dirlist:", dirlist
+ print("Dirlist: %s" % dirlist)
# copy this demo onto the server
try:
sftp.mkdir("demo_sftp_folder")
except IOError:
- print '(assuming demo_sftp_folder/ already exists)'
- sftp.open('demo_sftp_folder/README', 'w').write('This was created by demo_sftp.py.\n')
- data = open('demo_sftp.py', 'r').read()
+ print('(assuming demo_sftp_folder/ already exists)')
+ with sftp.open('demo_sftp_folder/README', 'w') as f:
+ f.write('This was created by demo_sftp.py.\n')
+ with open('demo_sftp.py', 'r') as f:
+ data = f.read()
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
- data = sftp.open('demo_sftp_folder/README', 'r').read()
- open('README_demo_sftp', 'w').write(data)
- print 'copied README back here'
+ with sftp.open('demo_sftp_folder/README', 'r') as f:
+ data = f.read()
+ with open('README_demo_sftp', 'w') as f:
+ f.write(data)
+ print('copied README back here')
# BETTER: use the get() and put() methods
sftp.put('demo_sftp.py', 'demo_sftp_folder/demo_sftp.py')
@@ -109,8 +114,8 @@ try:
t.close()
-except Exception, e:
- print '*** Caught exception: %s: %s' % (e.__class__, e)
+except Exception as e:
+ print('*** Caught exception: %s: %s' % (e.__class__, e))
traceback.print_exc()
try:
t.close()
diff --git a/demos/demo_simple.py b/demos/demo_simple.py
index 50f344a..ae631e4 100755
--- a/demos/demo_simple.py
+++ b/demos/demo_simple.py
@@ -25,9 +25,13 @@ import os
import socket
import sys
import traceback
+from paramiko.py3compat import input
import paramiko
-import interactive
+try:
+ import interactive
+except ImportError:
+ from . import interactive
# setup logging
@@ -40,9 +44,9 @@ if len(sys.argv) > 1:
if hostname.find('@') >= 0:
username, hostname = hostname.split('@')
else:
- hostname = raw_input('Hostname: ')
+ hostname = input('Hostname: ')
if len(hostname) == 0:
- print '*** Hostname required.'
+ print('*** Hostname required.')
sys.exit(1)
port = 22
if hostname.find(':') >= 0:
@@ -53,7 +57,7 @@ if hostname.find(':') >= 0:
# get username
if username == '':
default_username = getpass.getuser()
- username = raw_input('Username [%s]: ' % default_username)
+ username = input('Username [%s]: ' % default_username)
if len(username) == 0:
username = default_username
password = getpass.getpass('Password for %s@%s: ' % (username, hostname))
@@ -64,18 +68,17 @@ try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
- print '*** Connecting...'
+ print('*** Connecting...')
client.connect(hostname, port, username, password)
chan = client.invoke_shell()
- print repr(client.get_transport())
- print '*** Here we go!'
- print
+ print(repr(client.get_transport()))
+ print('*** Here we go!\n')
interactive.interactive_shell(chan)
chan.close()
client.close()
-except Exception, e:
- print '*** Caught exception: %s: %s' % (e.__class__, e)
+except Exception as e:
+ print('*** Caught exception: %s: %s' % (e.__class__, e))
traceback.print_exc()
try:
client.close()
diff --git a/demos/forward.py b/demos/forward.py
index 5048c77..96e1700 100644
--- a/demos/forward.py
+++ b/demos/forward.py
@@ -30,7 +30,11 @@ import getpass
import os
import socket
import select
-import SocketServer
+try:
+ import SocketServer
+except ImportError:
+ import socketserver as SocketServer
+
import sys
from optparse import OptionParser
@@ -54,7 +58,7 @@ class Handler (SocketServer.BaseRequestHandler):
chan = self.ssh_transport.open_channel('direct-tcpip',
(self.chain_host, self.chain_port),
self.request.getpeername())
- except Exception, e:
+ except Exception as e:
verbose('Incoming request to %s:%d failed: %s' % (self.chain_host,
self.chain_port,
repr(e)))
@@ -98,7 +102,7 @@ def forward_tunnel(local_port, remote_host, remote_port, transport):
def verbose(s):
if g_verbose:
- print s
+ print(s)
HELP = """\
@@ -165,8 +169,8 @@ def main():
try:
client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile,
look_for_keys=options.look_for_keys, password=password)
- except Exception, e:
- print '*** Failed to connect to %s:%d: %r' % (server[0], server[1], e)
+ except Exception as e:
+ print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e))
sys.exit(1)
verbose('Now forwarding port %d to %s:%d ...' % (options.port, remote[0], remote[1]))
@@ -174,7 +178,7 @@ def main():
try:
forward_tunnel(options.port, remote[0], remote[1], client.get_transport())
except KeyboardInterrupt:
- print 'C-c: Port forwarding stopped.'
+ print('C-c: Port forwarding stopped.')
sys.exit(0)
diff --git a/demos/interactive.py b/demos/interactive.py
index f3be74d..7138cd6 100644
--- a/demos/interactive.py
+++ b/demos/interactive.py
@@ -19,6 +19,7 @@
import socket
import sys
+from paramiko.py3compat import u
# windows does not have termios...
try:
@@ -49,9 +50,9 @@ def posix_shell(chan):
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
- x = chan.recv(1024)
+ x = u(chan.recv(1024))
if len(x) == 0:
- print '\r\n*** EOF\r\n',
+ sys.stdout.write('\r\n*** EOF\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
diff --git a/demos/rforward.py b/demos/rforward.py
index 4a5d2e4..ae70670 100755
--- a/demos/rforward.py
+++ b/demos/rforward.py
@@ -46,7 +46,7 @@ def handler(chan, host, port):
sock = socket.socket()
try:
sock.connect((host, port))
- except Exception, e:
+ except Exception as e:
verbose('Forwarding request to %s:%d failed: %r' % (host, port, e))
return
@@ -82,7 +82,7 @@ def reverse_forward_tunnel(server_port, remote_host, remote_port, transport):
def verbose(s):
if g_verbose:
- print s
+ print(s)
HELP = """\
@@ -150,8 +150,8 @@ def main():
try:
client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile,
look_for_keys=options.look_for_keys, password=password)
- except Exception, e:
- print '*** Failed to connect to %s:%d: %r' % (server[0], server[1], e)
+ except Exception as e:
+ print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e))
sys.exit(1)
verbose('Now forwarding remote port %d to %s:%d ...' % (options.port, remote[0], remote[1]))
@@ -159,7 +159,7 @@ def main():
try:
reverse_forward_tunnel(options.port, remote[0], remote[1], client.get_transport())
except KeyboardInterrupt:
- print 'C-c: Port forwarding stopped.'
+ print('C-c: Port forwarding stopped.')
sys.exit(0)