2 # -*- encoding: utf-8; py-indent-offset: 4 -*-
3 # +------------------------------------------------------------------+
4 # | ____ _ _ __ __ _ __ |
5 # | / ___| |__ ___ ___| | __ | \/ | |/ / |
6 # | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
7 # | | |___| | | | __/ (__| < | | | | . \ |
8 # | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
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.
38 USAGE: check_sftp [OPTIONS] HOST
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.
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
90 opts
, args
= getopt
.getopt(sys
.argv
[1:], short_options
, long_options
)
91 except getopt
.GetoptError
, err
:
92 sys
.stderr
.write("%s\n" % err
)
96 if opt
in ['-h', 'help']:
98 elif opt
in ['--host']:
100 elif opt
in ['--user']:
102 elif opt
in ['--secret']:
104 elif opt
in ['--private-key']:
106 elif opt
in ['--port']:
108 elif opt
in ['--timeout']:
109 opt_timeout
= float(arg
)
110 elif opt
in ['--put-local']:
112 elif opt
in ['--put-remote']:
114 elif opt
in ['--get-local']:
116 elif opt
in ['--get-remote']:
118 elif opt
in ['--get-timestamp']:
120 elif opt
in ['-v', '--verbose']:
125 client
= paramiko
.SSHClient()
126 client
.set_missing_host_key_policy(paramiko
.AutoAddPolicy())
128 client
.connect(opt_host
, username
=opt_user
, password
=opt_pass
, timeout
=opt_timeout
)
130 client
.connect(opt_host
, username
=opt_user
, pkey
=opt_key
, timeout
=opt_timeout
)
134 def get_paths(omd_root
, working_dir
):
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
)
143 paths
["remote_put_path"] = "%s/%s" % (working_dir
, put_filename
)
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
)
152 paths
["local_get_path"] = "%s/%s" % (omd_root
, get_filename
)
155 paths
["timestamp_filename"] = opt_timestamp
.split("/")[-1]
156 paths
["timestamp_path"] = "%s/%s" % (working_dir
, opt_timestamp
)
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")
174 sftp
.put(paths
["local_put_path"], \
175 paths
["remote_put_path"])
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
))
197 try: # Establish connection
198 client
= connection()
199 sftp
= client
.open_sftp()
200 messages
.append("Login successful")
205 write_out(2, "Connection failed!")
207 # Let's prepare for some other tests...
208 omd_root
= os
.getenv("OMD_ROOT")
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
)
221 messages
.append("Successfully put file to SFTP server")
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:
232 messages
.append("Successfully got file from SFTP server")
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
)
243 messages
.append("Timestamp of %s is: %s" % \
244 (paths
["timestamp_filename"], \
245 time
.ctime(file_stats
.st_mtime
)))
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
))