Cleanup config.nodes_of
[check_mk.git] / active_checks / check_sftp
blob0749f6966a7024470a888b92a289d1d85e798e4e
1 #!/usr/bin/env python
2 # -*- encoding: utf-8; py-indent-offset: 4 -*-
3 # +------------------------------------------------------------------+
4 # | ____ _ _ __ __ _ __ |
5 # | / ___| |__ ___ ___| | __ | \/ | |/ / |
6 # | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
7 # | | |___| | | | __/ (__| < | | | | . \ |
8 # | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
9 # | |
10 # | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
11 # +------------------------------------------------------------------+
13 # This file is part of Check_MK.
14 # The official homepage is at http://mathias-kettner.de/check_mk.
16 # check_mk is free software; you can redistribute it and/or modify it
17 # under the terms of the GNU General Public License as published by
18 # the Free Software Foundation in version 2. check_mk is distributed
19 # in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
20 # out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
21 # PARTICULAR PURPOSE. See the GNU General Public License for more de-
22 # tails. You should have received a copy of the GNU General Public
23 # License along with GNU Make; see the file COPYING. If not, write
24 # to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
25 # Boston, MA 02110-1301 USA.
27 import os
28 import sys
29 import time
30 import getopt
31 import paramiko
33 sftp = None
36 def usage():
37 sys.stderr.write("""
38 USAGE: check_sftp [OPTIONS] HOST
40 OPTIONS:
41 --host HOST SFTP server address
42 --user USER Username for sftp login
43 --secret SECRET Secret/Password for sftp login
44 --private-key KEY Private Key for sftp login
45 --port PORT Alternative port number (default is 22 for the connection)
46 --get-remote FILE Path to the file which to pull from SFTP server (e.g.
47 /tmp/testfile.txt)
48 --get-local PATH Path to store the pulled file locally (e.g. $OMD_ROOT/tmp/)
49 --put-local FILE Path to the file to push to the sftp server. See above for example
50 --put-remote PATH Path to save the pushed file (e.g. /tmp/)
51 --get-timestamp PATH Path to the file for getting the timestamp of this file
52 --timeout SECONDS Set timeout for connection (default is 10 seconds)
53 --verbose Output some more detailed information
54 -h, --help Show this help message and exit
55 """)
56 sys.exit(1)
59 opt_host = None
60 opt_user = None
61 opt_pass = None
62 opt_key = None
63 opt_port = 22
64 opt_get_remote = None
65 opt_get_local = None
66 opt_put_local = None
67 opt_put_remote = None
68 opt_timestamp = None
69 opt_timeout = 10.0
70 opt_verbose = False
72 short_options = 'hv'
73 long_options = [
74 'host=',
75 'user=',
76 'secret=',
77 'privat-key',
78 'port=',
79 'get-remote=',
80 'get-local=',
81 'put-local=',
82 'put-remote=',
83 'get-timestamp=',
84 'verbose',
85 'help',
86 'timeout=',
89 try:
90 opts, args = getopt.getopt(sys.argv[1:], short_options, long_options)
91 except getopt.GetoptError, err:
92 sys.stderr.write("%s\n" % err)
93 sys.exit(1)
95 for opt, arg in opts:
96 if opt in ['-h', 'help']:
97 usage()
98 elif opt in ['--host']:
99 opt_host = arg
100 elif opt in ['--user']:
101 opt_user = arg
102 elif opt in ['--secret']:
103 opt_pass = arg
104 elif opt in ['--private-key']:
105 opt_pass = arg
106 elif opt in ['--port']:
107 opt_port = int(arg)
108 elif opt in ['--timeout']:
109 opt_timeout = float(arg)
110 elif opt in ['--put-local']:
111 opt_put_local = arg
112 elif opt in ['--put-remote']:
113 opt_put_remote = arg
114 elif opt in ['--get-local']:
115 opt_get_local = arg
116 elif opt in ['--get-remote']:
117 opt_get_remote = arg
118 elif opt in ['--get-timestamp']:
119 opt_timestamp = arg
120 elif opt in ['-v', '--verbose']:
121 opt_verbose = True
124 def connection():
125 client = paramiko.SSHClient()
126 client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
127 if opt_key is None:
128 client.connect(opt_host, username=opt_user, password=opt_pass, timeout=opt_timeout)
129 else:
130 client.connect(opt_host, username=opt_user, pkey=opt_key, timeout=opt_timeout)
131 return client
134 def get_paths(omd_root, working_dir):
135 paths = {}
136 if opt_put_local:
137 put_filename = opt_put_local.split("/")[-1]
138 paths["put_filename"] = put_filename
139 paths["local_put_path"] = "%s/%s" % (omd_root, opt_put_local)
140 if len(opt_put_remote) > 0:
141 paths["remote_put_path"] = "%s/%s/%s" % (working_dir, opt_put_remote, put_filename)
142 else:
143 paths["remote_put_path"] = "%s/%s" % (working_dir, put_filename)
145 if opt_get_remote:
146 get_filename = opt_get_remote.split("/")[-1]
147 paths["get_filename"] = get_filename
148 paths["remote_get_path"] = "%s/%s" % (working_dir, opt_get_remote)
149 if len(opt_get_local) > 0:
150 paths["local_get_path"] = "%s/%s/%s" % (omd_root, opt_get_local, get_filename)
151 else:
152 paths["local_get_path"] = "%s/%s" % (omd_root, get_filename)
154 if opt_timestamp:
155 paths["timestamp_filename"] = opt_timestamp.split("/")[-1]
156 paths["timestamp_path"] = "%s/%s" % (working_dir, opt_timestamp)
158 return paths
161 def file_available(working_dir):
162 filename = opt_put_local.split("/")[-1]
163 return filename in sftp.listdir("%s/%s" % (working_dir, opt_put_remote))
166 def create_testfile(paths):
167 path = paths["local_put_path"]
168 if not os.path.isfile(path):
169 with open(path, "w") as f:
170 f.write("This is a test by Check_MK\n")
173 def put_file(paths):
174 sftp.put(paths["local_put_path"], \
175 paths["remote_put_path"])
178 def get_file(paths):
179 sftp.get(paths["remote_get_path"], \
180 paths["local_get_path"])
183 def get_timestamp(paths):
184 return sftp.stat(paths["timestamp_path"])
187 def write_out(state, message):
188 state_readable = ['OK', 'WARN', 'CRIT', 'UNKNOWN'][state]
189 sys.stdout.write('%s - %s\n' % (state_readable, message))
190 sys.exit(state)
193 def main():
194 global sftp
195 messages = []
196 states = []
197 try: # Establish connection
198 client = connection()
199 sftp = client.open_sftp()
200 messages.append("Login successful")
201 states.append(0)
202 except:
203 if opt_verbose:
204 raise
205 write_out(2, "Connection failed!")
207 # Let's prepare for some other tests...
208 omd_root = os.getenv("OMD_ROOT")
209 sftp.chdir(".")
210 working_dir = sftp.getcwd()
211 paths = get_paths(omd_root, working_dir)
212 testfile_remote = True
214 # .. and eventually execute them!
215 try: # Put a file to the server
216 if opt_put_local is not None:
217 create_testfile(paths)
218 testfile_remote = file_available(working_dir)
219 put_file(paths)
220 states.append(0)
221 messages.append("Successfully put file to SFTP server")
222 except:
223 if opt_verbose:
224 raise
225 states.append(2)
226 messages.append("Could not put file to SFTP server! (!!)")
228 try: # Get a file from the server
229 if opt_get_remote is not None:
230 get_file(paths)
231 states.append(0)
232 messages.append("Successfully got file from SFTP server")
233 except:
234 if opt_verbose:
235 raise
236 states.append(2)
237 messages.append("Could not get file from SFTP server! (!!)")
239 try: # Get timestamp of a remote file
240 if opt_timestamp is not None:
241 file_stats = get_timestamp(paths)
242 states.append(0)
243 messages.append("Timestamp of %s is: %s" % \
244 (paths["timestamp_filename"], \
245 time.ctime(file_stats.st_mtime)))
246 except:
247 if opt_verbose:
248 raise
249 states.append(2)
250 messages.append("Could not get timestamp of file! (!!)")
252 # Remove useless files
253 if not testfile_remote:
254 sftp.remove(paths["remote_put_path"])
256 write_out(max(states), ", ".join(messages))
259 main()