scutil 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. data/README +104 -0
  2. data/lib/scutil.rb +355 -0
  3. metadata +84 -0
data/README ADDED
@@ -0,0 +1,104 @@
1
+
2
+ =scutil
3
+ ==Description:
4
+
5
+ Scutil <em>(pronounced "scuttle")</em> is a small Ruby library that
6
+ makes using {Net::SSH}[http://net-ssh.github.com] to execute commands
7
+ on remote systems even more convenient.
8
+
9
+ It does this in three ways:
10
+
11
+ First, it defines Scutil.exec_command which abstracts the callbacks
12
+ and other setup necessary to connect to a system, execute a command,
13
+ and capture the output and return value of that command. You can
14
+ roughly think of it as a generic <em>"Capistrano lite"</em> in this
15
+ regard.
16
+
17
+ Second, it tracks the connections used on all systems and reuses
18
+ these connections where ever possible.
19
+
20
+ Finally, scutil takes away the burden of managing data transfers over
21
+ PTY connections. It automatically requests PTYs where needed and
22
+ makes them "binary safe" (this functionality is configurable and can
23
+ be disabled). PTYs are needed for some curses-based programs and,
24
+ most importantly in scutil's context, for sudo. A full discussion on
25
+ PTYs is beyond the scope of this documentation.
26
+
27
+ The "_automatic_" part of PTY requests comes from a regex in
28
+ Scutil.exec_command. Basically, if _sudo_ is at the start of the
29
+ command to be executed, scutil will request a PTY. Right now this
30
+ regex isn't configurable. In a near future release it will be. You
31
+ can force a PTY request by specifying +:scutil_force_pty+ in the
32
+ various _options_ arguments.
33
+
34
+ All of this syntactic sugar can be used as a simple class method with
35
+ Scutil.exec_command, as an instantiable class with Scutil::Exec, or as
36
+ a mixin with the module Scutil.
37
+
38
+ ==Synopsis:
39
+
40
+ You can use scutil in a few different ways, for more usage examples
41
+ see Scutil.
42
+
43
+ require 'scutil'
44
+
45
+ # Class method executed immediately:
46
+ Scutil.exec_command('servername1', 'username', 'pwd',
47
+ {
48
+ :keys => '~mas/.ssh/id_rsa',
49
+ :scutil_verbose => true
50
+ })
51
+
52
+
53
+ # Object to be used and reused:
54
+ exec = Scutil::Exec.new('servername2', 'mas',
55
+ { :keys => '~mas/.ssh/id_rsa' })
56
+ exec.exec_command("ls -l /")
57
+
58
+ return_value = exec.exec_command("grep -q ...")
59
+
60
+ # Tar up /usr/src/linux on the remote machine and write it to
61
+ # /var/tmp/linux.tar.gz on the local machine. Hostname, error
62
+ # message, and return value in the exception:
63
+ begin
64
+ exec.exec_command('sudo tar -C /usr/src -czf - linux', '/var/tmp/linux.tar.gz')
65
+ rescue Scutil::Error => err
66
+ puts "Message: " + err.message
67
+ puts "Hostname: " + err.hostname
68
+ puts "Exit status: #{err.command_exit_status}"
69
+ end
70
+
71
+ # Capture command output in a string:
72
+ require 'stringio'
73
+
74
+ command_output = StringIO.new
75
+ Scutil.exec_command('servername1', 'mas', 'sudo cat /root/secrets.txt', command_output)
76
+ puts command_output.string
77
+
78
+ == Installation:
79
+
80
+ gem install scutil
81
+
82
+ == License:
83
+
84
+ The MIT License (MIT)
85
+
86
+ Copyright (c) 2011 by Marc Soda
87
+
88
+ Permission is hereby granted, free of charge, to any person obtaining a copy
89
+ of this software and associated documentation files (the "Software"), to deal
90
+ in the Software without restriction, including without limitation the rights
91
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
92
+ copies of the Software, and to permit persons to whom the Software is
93
+ furnished to do so, subject to the following conditions:
94
+
95
+ The above copyright notice and this permission notice shall be included in
96
+ all copies or substantial portions of the Software.
97
+
98
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
99
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
100
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
101
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
102
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
103
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
104
+ THE SOFTWARE.
data/lib/scutil.rb ADDED
@@ -0,0 +1,355 @@
1
+
2
+ =begin
3
+ The MIT License (MIT)
4
+
5
+ Copyright (C) 2011 by Marc Soda
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ THE SOFTWARE.
24
+ =end
25
+
26
+ #begin
27
+ # require 'rubygems'
28
+ # gem 'net-ssh', ">= 2.1.0"
29
+ #rescue LoadError, NameError
30
+ #end
31
+
32
+ require 'net/ssh'
33
+
34
+ module Scutil
35
+ # Utiliy class to hold all the connections created, possibly for
36
+ # reuse later.
37
+ class ConnectionCache
38
+ attr_reader :cache
39
+ include Enumerable
40
+
41
+ def initialize
42
+ @cache = []
43
+ end
44
+
45
+ # Need each to mixin Enumerable
46
+ def each
47
+ @cache.each do |c|
48
+ yield c
49
+ end
50
+ end
51
+
52
+ def fetch(hostname)
53
+ each do |c|
54
+ return c if c.hostname == hostname
55
+ end
56
+ end
57
+
58
+ def exists?(hostname)
59
+ each do |c|
60
+ return true if c.hostname == hostname
61
+ end
62
+ false
63
+ end
64
+
65
+ def <<(conn)
66
+ @cache << conn
67
+ end
68
+
69
+ def to_s
70
+ @cache.join("\n")
71
+ end
72
+ end
73
+
74
+ # By default, buffer 10M of data before writing.
75
+ DEFAULT_BUFFER_SIZE = 0xA00000
76
+ SCUTIL_VERSION = '0.1'
77
+ @connection_cache = ConnectionCache.new
78
+ @buffer_size = DEFAULT_BUFFER_SIZE
79
+
80
+ class << self
81
+ # All successfully established connections end up here for reuse
82
+ # later.
83
+ attr_accessor :connection_cache
84
+ # Set to 10M by default, this can be adjusted to tell scutil when
85
+ # to write command output to _output_.
86
+ attr_accessor :buffer_size
87
+ end
88
+
89
+ # Wrapper for each connection to a system. Capabile of holding a
90
+ # standard connect (@connection) and and PTY connection
91
+ # (@pty_connection) for each system.
92
+ class SystemConnection
93
+ attr_reader :hostname,:pty_connection,:connection
94
+ def initialize(hostname, options={})
95
+ @hostname = hostname
96
+ @connection = nil
97
+ @pty_connection = nil
98
+ @options = options
99
+ end
100
+
101
+ # Return a connection for system. Checks to see if an established
102
+ # connection exists. If not it creates a new one. Requests a PTY
103
+ # if needed.
104
+ def get_connection(hostname, username, pty_needed=false, options={})
105
+ conn = nil
106
+ # Local map has precedence.
107
+ @options.merge!(options)
108
+
109
+ scrub_options @options
110
+
111
+ if (pty_needed)
112
+ if !@pty_connection.nil?
113
+ # Existing PTY connection
114
+ $stderr.print "[#{hostname}] Using existing connection (pty)\n" if @options[:scutil_verbose]
115
+ return @pty_connection
116
+ end
117
+
118
+ # New PTY connection
119
+ $stderr.print "[#{hostname}] Opening new channel (pty) to system...\n" if @options[:scutil_verbose]
120
+ conn = Net::SSH.start(hostname, username, @options)
121
+ @pty_connection = conn
122
+ else
123
+ if !@connection.nil?
124
+ # Existing non-PTY connection
125
+ $stderr.print "[#{hostname}] Using existing connection (non-pty)\n" if @options[:scutil_verbose]
126
+ return @connection
127
+ end
128
+
129
+ # New non-PTY connection
130
+ $stderr.print "[#{hostname}] Opening channel (non-pty) to system...\n" if @options[:scutil_verbose]
131
+ conn = Net::SSH.start(hostname, username, @options)
132
+ @connection = conn
133
+ end
134
+
135
+ return conn
136
+ end
137
+
138
+ # Remove scutil specific options. The rest go to Net::SSH.
139
+ def scrub_options(options)
140
+ options.delete(:scutil_verbose) if (options.has_key?(:scutil_verbose))
141
+ options.delete(:scutil_force_pty) if (options.has_key?(:scutil_force_pty))
142
+ end
143
+
144
+ def to_s
145
+ "#{self.class}: #{@name}, @connection = #{@connection}, @pty_connection = #{@pty_connection}"
146
+ end
147
+ end
148
+
149
+ # Instantiate this class if you wish to use scutil as an object.
150
+ # For example:
151
+ #
152
+ # exec = Scutil::Exec.new('severname', 'mas')
153
+ #
154
+ # exec.exec_command('echo "foo"')
155
+ #
156
+ # exec.exec_command('echo "bar"; sudo whoami', "",
157
+ # { :scutil_force_pty => true,
158
+ # :scutil_verbose => true
159
+ # })
160
+
161
+ class Exec
162
+ include Scutil
163
+ attr_reader :hostname,:username
164
+
165
+ def initialize(hostname, username, options={})
166
+ @hostname = hostname
167
+ @username = username
168
+ @options = options
169
+ end
170
+
171
+ # See Scutil.exec_command. Takes _cmd_ and optionally _output_,
172
+ # and _options_. Other arguments specified at class
173
+ # initialization.
174
+ #
175
+ # The _options_ specified here will take precedence over those
176
+ # specified in the constructor.
177
+ def exec_command(cmd, output=nil, options={})
178
+ # Local map has precedence.
179
+ @options.merge!(options)
180
+ Scutil.exec_command(@hostname, @username, cmd, output, @options)
181
+ end
182
+ end
183
+
184
+ class << self
185
+
186
+ # Scutil.exec_command is used to execute a command, specified in
187
+ # _cmd_, on a remote system. The return value and any ouput of
188
+ # the command are captured.
189
+ #
190
+ # If _output_ is a string it will be treated as a filename to be
191
+ # opened (mode 'w+') and all command output will be written to
192
+ # this file. If _output_ is an IO object it will be treated as an
193
+ # open file handle.* Finally, if _output_ is omitted, or an empty
194
+ # string, all command output will be directed to _$stdout_.
195
+ #
196
+ # <em>**NB:* This isn't actually true. The only check made is to
197
+ # see if _output_ responds to +:write+. The idea being that not
198
+ # only will a file handle have a +write+ method but also something
199
+ # like +StringIO+. Using +StringIO+ here makes it easy to capture
200
+ # the command's output in a string. Suggestions on a better way
201
+ # to do this are definitely welcome.</em>
202
+ #
203
+ # Scutil will automatically request a PTY if _sudo_ is at the
204
+ # start of _cmd_. Right now the regex that drives this isn't
205
+ # configurable. In a near future release it will be. You can
206
+ # force a PTY request by specifying +:scutil_force_pty+ in
207
+ # _options_.
208
+ #
209
+ # Scutil.exec_command takes the following options:
210
+ #
211
+ # * :scutil_verbose => Extra output.
212
+ # * :scutil_force_pty => If true, force a PTY request for every channel.
213
+ #
214
+ # In addition, any other options passed Scutil.exec_command will
215
+ # be passed on to Net::SSH, _except_ those prefixed with
216
+ # _scutil__.
217
+ #
218
+ # All calls to Scutil.exec_command, regardless of the way it's
219
+ # used, will return the remote command's return value.
220
+ #
221
+ # retval = Scutil.exec_command('hostname', 'username', '/bin/true')
222
+ # puts "True is false!" if retval != 0
223
+
224
+ def exec_command(hostname, username, cmd, output=nil, options={})
225
+ # Do we need a PTY?
226
+ # TODO: Add a callback to specify custom pty determinate function.
227
+ if (options[:scutil_force_pty])
228
+ pty_needed = true
229
+ else
230
+ pty_needed = (cmd =~ /^\s*sudo/) ? true : false
231
+ end
232
+
233
+ # Check for an existing connection in the cache based on the hostname. If the
234
+ # hostname exists find a suitable connection.
235
+ conn = nil
236
+ begin
237
+ if (Scutil.connection_cache.exists?(hostname))
238
+ sys_conn = Scutil.connection_cache.fetch(hostname)
239
+ conn = sys_conn.get_connection(hostname, username, pty_needed, options)
240
+ else
241
+ sys_conn = SystemConnection.new(hostname)
242
+ $stderr.print "[#{hostname}] Adding new connection to cache\n" if options[:scutil_verbose]
243
+ # Call get_connection first. Don't add to cache unless established.
244
+ conn = sys_conn.get_connection(hostname, username, pty_needed, options)
245
+ Scutil.connection_cache << sys_conn
246
+ end
247
+ rescue Net::SSH::AuthenticationFailed => err
248
+ raise Scutil::Error.new("Error: Authenication failed for user: #{username}", hostname)
249
+ end
250
+
251
+ fh = $stdout
252
+ if (output.nil?)
253
+ fh = $stdout
254
+ elsif (output.respond_to?(:write))
255
+ # XXX: This may not be a safe assumuption...
256
+ fh = output
257
+ elsif (output.class == String)
258
+ fh = File.open(output, 'w+') unless output.empty?
259
+ else
260
+ raise Scutil::Error.new("Error: Invalid output object type: #{output.class}.", hostname)
261
+ end
262
+
263
+ # Setup channel callbacks
264
+ odata = ""
265
+ edata = ""
266
+ exit_status = 0
267
+ channel = conn.open_channel do |channel|
268
+ $stderr.print "[#{conn.host}:#{channel.local_id}] Setting up callbacks...\n" if options[:scutil_verbose]
269
+ if (pty_needed)
270
+ $stderr.print "[#{conn.host}:#{channel.local_id}] Requesting PTY...\n" if options[:scutil_verbose]
271
+ # OPOST seems necessary, CS8 makes sense. Revisit after broader testing.
272
+ channel.request_pty(:modes => { Net::SSH::Connection::Term::CS8 => 1, Net::SSH::Connection::Term::OPOST => 0 } ) do |ch, success|
273
+ raise Scutil::Error.new("Failed to get a PTY", hostname) if !success
274
+ end
275
+ end
276
+
277
+ channel.on_data do |ch, data|
278
+ # $stderr.print "on_data: #{data.size}\n" if options[:scutil_verbose]
279
+ odata += data
280
+
281
+ # Only buffer some of the output before writing to disk.
282
+ if (odata.size >= 0xA00000) # 10M
283
+ fh.write odata
284
+ odata = ""
285
+ end
286
+ end
287
+
288
+ channel.on_extended_data do |ch, type, data|
289
+ # $stderr.print "on_extended_data: #{data.size}\n" if options[:scutil_verbose]
290
+ edata += data
291
+ end
292
+
293
+ channel.on_close do |ch|
294
+ $stderr.print "[#{conn.host}:#{channel.local_id}] on_close\n" if options[:scutil_verbose]
295
+ end
296
+
297
+ channel.on_open_failed do |ch, code, desc|
298
+ raise Scutil::Error.new("Failed to open channel: #{desc}", hostname, code) if !success
299
+ end
300
+
301
+ channel.on_request("exit-status") do |ch, data|
302
+ exit_status = data.read_long
303
+ end
304
+
305
+ channel.exec(cmd)
306
+ end
307
+
308
+ conn.loop
309
+
310
+ # Write whatever is left
311
+ fh.write odata
312
+
313
+ # If extended_data was recieved there was a problem...
314
+ raise Scutil::Error.new("Error: #{edata}", hostname, exit_status) unless (edata.empty?)
315
+
316
+ # The return value of the remote command.
317
+ return exit_status
318
+ end
319
+ end
320
+
321
+ # def xfer_file(hostname, username, src, dst, direction=:to, command=nil, options={})
322
+
323
+ # end
324
+ end
325
+
326
+ # Exception class for scutil. The system, error message, and return
327
+ # value of the remote command are stored here on error.
328
+ #
329
+ # begin
330
+ # Scutil.exec_command('ls -al /root')
331
+ # rescue Scutil::Error => err
332
+ # puts "Message: " + err.message
333
+ # puts "Hostname: " + err.hostname
334
+ # puts "Exit status: #{err.command_exit_status}"
335
+ # end
336
+ #
337
+ # Will produce:
338
+ #
339
+ # Message: Error: ls: /root: Permission denied
340
+ # Hostname: server.name.com
341
+ # Exit status: 2
342
+ #
343
+ class Scutil::Error < StandardError
344
+ attr_reader :hostname,:message,:command_exit_status
345
+
346
+ def initialize(message=nil, hostname=nil, command_exit_status=-1)
347
+ @message = message
348
+ @hostname = hostname
349
+ @command_exit_status = command_exit_status
350
+ end
351
+
352
+ def to_s
353
+ "Message: #{@message}\nHostname: #{@hostname}\nExit status: #{command_exit_status}\n"
354
+ end
355
+ end
metadata ADDED
@@ -0,0 +1,84 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: scutil
3
+ version: !ruby/object:Gem::Version
4
+ hash: 25
5
+ prerelease: false
6
+ segments:
7
+ - 0
8
+ - 1
9
+ - 1
10
+ version: 0.1.1
11
+ platform: ruby
12
+ authors:
13
+ - Marc Soda
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2011-09-17 00:00:00 -04:00
19
+ default_executable:
20
+ dependencies:
21
+ - !ruby/object:Gem::Dependency
22
+ name: net-ssh
23
+ prerelease: false
24
+ requirement: &id001 !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ hash: 11
30
+ segments:
31
+ - 2
32
+ - 1
33
+ - 0
34
+ version: 2.1.0
35
+ type: :runtime
36
+ version_requirements: *id001
37
+ description: " Scutil is a library for conveniently executing commands \n remotely via SSH.\n"
38
+ email: marcantoniosr@gmail.com
39
+ executables: []
40
+
41
+ extensions: []
42
+
43
+ extra_rdoc_files:
44
+ - README
45
+ files:
46
+ - lib/scutil.rb
47
+ - README
48
+ has_rdoc: true
49
+ homepage: http://scutil.github.com
50
+ licenses:
51
+ - MIT
52
+ post_install_message:
53
+ rdoc_options:
54
+ - --title
55
+ - SSH Command UTILity
56
+ require_paths:
57
+ - lib
58
+ required_ruby_version: !ruby/object:Gem::Requirement
59
+ none: false
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ hash: 3
64
+ segments:
65
+ - 0
66
+ version: "0"
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ none: false
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ hash: 3
73
+ segments:
74
+ - 0
75
+ version: "0"
76
+ requirements: []
77
+
78
+ rubyforge_project:
79
+ rubygems_version: 1.3.7
80
+ signing_key:
81
+ specification_version: 3
82
+ summary: SSH Command UTILity
83
+ test_files: []
84
+