|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +"""Example script for authentication with Python callback function using an OAuth token""" |
| 4 | + |
| 5 | +from __future__ import print_function |
| 6 | + |
| 7 | +import argparse |
| 8 | +import socket |
| 9 | +import os |
| 10 | +import pwd |
| 11 | +import functools |
| 12 | + |
| 13 | + |
| 14 | +from ssh2.session import Session |
| 15 | + |
| 16 | + |
| 17 | +USERNAME = pwd.getpwuid(os.geteuid()).pw_name |
| 18 | + |
| 19 | +parser = argparse.ArgumentParser() |
| 20 | + |
| 21 | +parser.add_argument('password', help="User password") |
| 22 | +parser.add_argument('oauth', help="OAUTH key to use for authentication") |
| 23 | +parser.add_argument('cmd', help="Command to run") |
| 24 | +parser.add_argument('--host', dest='host', |
| 25 | + default='localhost', |
| 26 | + help='Host to connect to') |
| 27 | +parser.add_argument('--port', dest='port', default=22, help="Port to connect on", type=int) |
| 28 | +parser.add_argument('-u', dest='user', default=USERNAME, help="User name to authenticate as") |
| 29 | + |
| 30 | + |
| 31 | +def oauth_handler(name, instruction, prompts, password, oauth): |
| 32 | + responses = [] |
| 33 | + |
| 34 | + for prompt in prompts: |
| 35 | + if "Password:" in prompt: |
| 36 | + responses.append(password) |
| 37 | + if "One-time password (OATH) for" in prompt: |
| 38 | + responses.append(oauth) |
| 39 | + |
| 40 | + return responses |
| 41 | + |
| 42 | +def main(): |
| 43 | + args = parser.parse_args() |
| 44 | + |
| 45 | + callback = functools.partial(oauth_handler,password=args.password,oauth=args.oauth) |
| 46 | + |
| 47 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 48 | + sock.connect((args.host, args.port)) |
| 49 | + s = Session() |
| 50 | + s.handshake(sock) |
| 51 | + s.userauth_keyboardinteractive_callback(args.user, callback) |
| 52 | + chan = s.open_session() |
| 53 | + chan.execute(args.cmd) |
| 54 | + size, data = chan.read() |
| 55 | + while size > 0: |
| 56 | + print(data) |
| 57 | + size, data = chan.read() |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + main() |
0 commit comments