Skip to content

Commit

Permalink
Blacken 2.0 with black 18.6b4
Browse files Browse the repository at this point in the history
  • Loading branch information
bitprophet committed Sep 17, 2018
1 parent 025a250 commit 4e31612
Show file tree
Hide file tree
Showing 76 changed files with 4,452 additions and 3,326 deletions.
85 changes: 45 additions & 40 deletions demos/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
from paramiko.py3compat import input

import paramiko

try:
import interactive
except ImportError:
Expand All @@ -42,79 +43,81 @@ def agent_auth(transport, username):
Attempt to authenticate to the given transport using any of the private
keys available from an SSH agent.
"""

agent = paramiko.Agent()
agent_keys = agent.get_keys()
if len(agent_keys) == 0:
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 = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
default_auth = "p"
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 = input('RSA key [%s]: ' % default_path)
if auth == "r":
default_path = os.path.join(os.environ["HOME"], ".ssh", "id_rsa")
path = input("RSA key [%s]: " % default_path)
if len(path) == 0:
path = default_path
try:
key = paramiko.RSAKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('RSA key password: ')
password = getpass.getpass("RSA key password: ")
key = paramiko.RSAKey.from_private_key_file(path, password)
t.auth_publickey(username, key)
elif auth == 'd':
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
path = input('DSS key [%s]: ' % default_path)
elif auth == "d":
default_path = os.path.join(os.environ["HOME"], ".ssh", "id_dsa")
path = input("DSS key [%s]: " % default_path)
if len(path) == 0:
path = default_path
try:
key = paramiko.DSSKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('DSS key password: ')
password = getpass.getpass("DSS key password: ")
key = paramiko.DSSKey.from_private_key_file(path, password)
t.auth_publickey(username, key)
else:
pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
pw = getpass.getpass("Password for %s@%s: " % (username, hostname))
t.auth_password(username, pw)


# setup logging
paramiko.util.log_to_file('demo.log')
paramiko.util.log_to_file("demo.log")

username = ''
username = ""
if len(sys.argv) > 1:
hostname = sys.argv[1]
if hostname.find('@') >= 0:
username, hostname = hostname.split('@')
if hostname.find("@") >= 0:
username, hostname = hostname.split("@")
else:
hostname = input('Hostname: ')
hostname = input("Hostname: ")
if len(hostname) == 0:
print('*** Hostname required.')
print("*** Hostname required.")
sys.exit(1)
port = 22
if hostname.find(':') >= 0:
hostname, portstr = hostname.split(':')
if hostname.find(":") >= 0:
hostname, portstr = hostname.split(":")
port = int(portstr)

# now connect
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, port))
except Exception as e:
print('*** Connect failed: ' + str(e))
print("*** Connect failed: " + str(e))
traceback.print_exc()
sys.exit(1)

Expand All @@ -123,60 +126,62 @@ def manual_auth(username, hostname):
try:
t.start_client()
except paramiko.SSHException:
print('*** SSH negotiation failed.')
print("*** SSH negotiation failed.")
sys.exit(1)

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:
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:
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 hostname not in keys:
print('*** WARNING: Unknown host key!')
print("*** WARNING: Unknown host key!")
elif key.get_name() not in keys[hostname]:
print('*** WARNING: Unknown host key!')
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 == '':
if username == "":
default_username = getpass.getuser()
username = input('Username [%s]: ' % default_username)
username = input("Username [%s]: " % default_username)
if len(username) == 0:
username = default_username

agent_auth(t, username)
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!\n')
print("*** Here we go!\n")
interactive.interactive_shell(chan)
chan.close()
t.close()

except Exception as e:
print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
print("*** Caught exception: " + str(e.__class__) + ": " + str(e))
traceback.print_exc()
try:
t.close()
except:
pass
sys.exit(1)


130 changes: 89 additions & 41 deletions demos/demo_keygen.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,62 +28,97 @@
from paramiko.ssh_exception import SSHException
from paramiko.py3compat import u

usage="""
usage = """
%prog [-v] [-b bits] -t type [-N new_passphrase] [-f output_keyfile]"""

default_values = {
"ktype": "dsa",
"bits": 1024,
"filename": "output",
"comment": ""
"comment": "",
}

key_dispatch_table = {
'dsa': DSSKey,
'rsa': RSAKey,
}
key_dispatch_table = {"dsa": DSSKey, "rsa": RSAKey}


def progress(arg=None):

if not arg:
sys.stdout.write('0%\x08\x08\x08 ')
sys.stdout.write("0%\x08\x08\x08 ")
sys.stdout.flush()
elif arg[0] == 'p':
sys.stdout.write('25%\x08\x08\x08\x08 ')
elif arg[0] == "p":
sys.stdout.write("25%\x08\x08\x08\x08 ")
sys.stdout.flush()
elif arg[0] == 'h':
sys.stdout.write('50%\x08\x08\x08\x08 ')
elif arg[0] == "h":
sys.stdout.write("50%\x08\x08\x08\x08 ")
sys.stdout.flush()
elif arg[0] == 'x':
sys.stdout.write('75%\x08\x08\x08\x08 ')
elif arg[0] == "x":
sys.stdout.write("75%\x08\x08\x08\x08 ")
sys.stdout.flush()

if __name__ == '__main__':

phrase=None
pfunc=None
if __name__ == "__main__":

phrase = None
pfunc = None

parser = OptionParser(usage=usage)
parser.add_option("-t", "--type", type="string", dest="ktype",
parser.add_option(
"-t",
"--type",
type="string",
dest="ktype",
help="Specify type of key to create (dsa or rsa)",
metavar="ktype", default=default_values["ktype"])
parser.add_option("-b", "--bits", type="int", dest="bits",
help="Number of bits in the key to create", metavar="bits",
default=default_values["bits"])
parser.add_option("-N", "--new-passphrase", dest="newphrase",
help="Provide new passphrase", metavar="phrase")
parser.add_option("-P", "--old-passphrase", dest="oldphrase",
help="Provide old passphrase", metavar="phrase")
parser.add_option("-f", "--filename", type="string", dest="filename",
help="Filename of the key file", metavar="filename",
default=default_values["filename"])
parser.add_option("-q", "--quiet", default=False, action="store_false",
help="Quiet")
parser.add_option("-v", "--verbose", default=False, action="store_true",
help="Verbose")
parser.add_option("-C", "--comment", type="string", dest="comment",
help="Provide a new comment", metavar="comment",
default=default_values["comment"])
metavar="ktype",
default=default_values["ktype"],
)
parser.add_option(
"-b",
"--bits",
type="int",
dest="bits",
help="Number of bits in the key to create",
metavar="bits",
default=default_values["bits"],
)
parser.add_option(
"-N",
"--new-passphrase",
dest="newphrase",
help="Provide new passphrase",
metavar="phrase",
)
parser.add_option(
"-P",
"--old-passphrase",
dest="oldphrase",
help="Provide old passphrase",
metavar="phrase",
)
parser.add_option(
"-f",
"--filename",
type="string",
dest="filename",
help="Filename of the key file",
metavar="filename",
default=default_values["filename"],
)
parser.add_option(
"-q", "--quiet", default=False, action="store_false", help="Quiet"
)
parser.add_option(
"-v", "--verbose", default=False, action="store_true", help="Verbose"
)
parser.add_option(
"-C",
"--comment",
type="string",
dest="comment",
help="Provide a new comment",
metavar="comment",
default=default_values["comment"],
)

(options, args) = parser.parse_args()

Expand All @@ -95,26 +130,31 @@ def progress(arg=None):
globals()[o] = getattr(options, o, default_values[o.lower()])

if options.newphrase:
phrase = getattr(options, 'newphrase')
phrase = getattr(options, "newphrase")

if options.verbose:
pfunc = progress
sys.stdout.write("Generating priv/pub %s %d bits key pair (%s/%s.pub)..." % (ktype, bits, filename, filename))
sys.stdout.write(
"Generating priv/pub %s %d bits key pair (%s/%s.pub)..."
% (ktype, bits, filename, filename)
)
sys.stdout.flush()

if ktype == 'dsa' and bits > 1024:
if ktype == "dsa" and bits > 1024:
raise SSHException("DSA Keys must be 1024 bits")

if ktype not in key_dispatch_table:
raise SSHException("Unknown %s algorithm to generate keys pair" % ktype)
raise SSHException(
"Unknown %s algorithm to generate keys pair" % ktype
)

# generating private key
prv = key_dispatch_table[ktype].generate(bits=bits, progress_func=pfunc)
prv.write_private_key_file(filename, password=phrase)

# generating public key
pub = key_dispatch_table[ktype](filename=filename, password=phrase)
with open("%s.pub" % filename, 'w') as f:
with open("%s.pub" % filename, "w") as f:
f.write("%s %s" % (pub.get_name(), pub.get_base64()))
if options.comment:
f.write(" %s" % comment)
Expand All @@ -123,4 +163,12 @@ def progress(arg=None):
print("done.")

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()))
print(
"Fingerprint: %d %s %s.pub (%s)"
% (
bits,
":".join([hash[i : 2 + i] for i in range(0, len(hash), 2)]),
filename,
ktype.upper(),
)
)
Loading

0 comments on commit 4e31612

Please sign in to comment.