1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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))
|