From 6e93465f7005bfbf63b064d0c16d1b509cf3a682 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Sat, 28 Aug 2010 11:27:19 +0200 Subject: example: Added a python ssh client. --- examples/sshclient.py | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100755 examples/sshclient.py diff --git a/examples/sshclient.py b/examples/sshclient.py new file mode 100755 index 00000000..ce9d5c8b --- /dev/null +++ b/examples/sshclient.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python + +import sys +from sys import stderr +from optparse import OptionParser + +import ssh + +def verify_server(session): + state = session.isServerKnown() + + # TODO Correctly check for server + if state != ssh.SSH_SERVER_KNOWN_OK: + return False + + return True + +def authenticate(session): + state = session.userauthAutopubkey() + + if state != ssh.SSH_AUTH_SUCCESS: + return False + + return True + +def connect(host, port): + session = ssh.Session() + + print "Trying to connect to " + host + ":" + str(port) + + session.setOption(ssh.SSH_OPTIONS_HOST, host) + session.setOption(ssh.SSH_OPTIONS_PORT, port) + + session.connect() + known = session.isServerKnown() + + if not verify_server(session): + session.disconnect() + return None + + print "Server is known" + + if not authenticate(session): + session.disconnect() + return None + + return session + +def execute(session): + channel = ssh.Channel(session) + + channel.openSession() + + print 'Execute: ps aux' + channel.requestExec('ps aux') + +# buf = '' +# while channel.read(buf, 1024) > 0: +# print buf + + channel.sendEof() + channel.close() + +def parse_command_line(args, usage): + parser = OptionParser(usage) + + parser.add_option("-p", "--port", dest="port", type="int", + help="The port to connect to") + + return parser.parse_args(args) + +def main(argv): + usage = "Usage: sshclient.py [options] host" + port = 22 + + (options, args) = parse_command_line(args = argv, usage = usage) + + if len(args) < 2: + print >> stderr, usage + return 1 + + host = args[1] + + if options.port: + port = options.port + + session = connect(host, port) + if not session: + return 1 + + execute(session) + + session.disconnect() + + return 0 + +if __name__ == "__main__": + sys.exit(main(sys.argv)) -- cgit v1.2.3