aboutsummaryrefslogtreecommitdiff
path: root/examples/sshclient.py
diff options
context:
space:
mode:
Diffstat (limited to 'examples/sshclient.py')
-rwxr-xr-xexamples/sshclient.py98
1 files changed, 98 insertions, 0 deletions
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))