- 论坛徽章:
- 1
|
本帖最后由 gtuiw 于 2013-03-20 14:49 编辑
我的实现方法就是每台机器都当作一台server,然后想执行什么命令,在一台机器上连接这些机器的端口,然后直接执行命令.
这方法类似于puppet的使用认证文件执行命令.我使用mac地址作认证信息.
很久没搞了,都不知道东南西北了.
我是使用ruby实现的,代码如下:- [b]Server[/b]
- 1 require 'socket'
- 2 require 'digest/sha1'
- 3 require "openssl"
- 4
- 5 priv_key = OpenSSL::PKey::RSA.new(1024)
- 6 pub_key = priv_key.public_key
- 7
- 8 host = ARGV[0] || 'localhost'
- 9 port = (ARGV[1] || 8888).to_i
- 10
- 11 server = TCPServer.new(host, port)
- 12
- 13 sockets = [server]
- 14
- 15 while true
- 16 ready = select(sockets)
- 17 readable = ready[0]
- 18 readable.each do |socket|
- 19 if socket === server
- 20 session = socket.accept
- 21 temp = session.recv(100)
- 22 recv_data = temp.unpack("m")
- 23 if recv_data[0] === 'c8:2a:14:17:31:15'
- 24 session.print pub_key
- 25 exec_command = session.recv(1000)
- 26 puts "Received data..."
- 27 msg = priv_key.private_decrypt(exec_command)
- 28 print msg
- 29 puts "Executing command: #{msg}"
- 30 `#{msg}`
- 31 else
- 32 puts "The message could not be validated!"
- 33 puts false
- 34 end
- 35 end
- 36 end
- 37 end
复制代码- [b]Client[/b]
- 1 #!/usr/bin/env ruby
- 2 require 'socket'
- 3 require 'digest/sha1'
- 4 require "openssl"
- 5
- 6 RE = %r/(?:[^:\-]|\A)(?:[0-9A-F][0-9A-F][:\-]){5}[0-9A-F][0-9A-F](?:[^:\-]|\Z)/io
- 7 platform = RUBY_PLATFORM.downcase
- 8 output = `#{platform =~ /linux/ ? '/sbin/ifconfig' : 'ifconfig'}`
- 9
- 10 def parse(output)
- 11 lines = output.split(/\n/)
- 12 candidates = lines.select{|line| line =~ RE}
- 13 raise 'no mac address candidates' unless candidates.first
- 14 candidates.map!{|c| c[RE].strip}
- 15 end
- 16
- 17 begin
- 18 client = TCPSocket.open('localhost', 8888)
- 19 puts "connected!\n\n"
- 20 macaddr = parse(output)
- 21 client.print macaddr.pack("m")
- 22 temp = ""
- 23 6.times do
- 24 temp << client.gets
- 25 end
- 26 puts "Received public 1024 RSA key!\n\n"
- 27 public_key = OpenSSL::PKey::RSA.new(temp)
- 28
- 29 msg = 'echo "hello"'
- 30 command = public_key.public_encrypt("#{msg}")
- 31 print "Sending the command...."
- 32 client.send(command,0)
- 33 puts "sent!"
- 34 rescue => e
- 35 puts "Something terrible happened..."
- 36 puts e
- 37 retry
- 38 end
- 39 client.close
复制代码 |
|