File: public_key.rb

package info (click to toggle)
vagrant 2.2.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 8,072 kB
  • sloc: ruby: 80,731; sh: 369; makefile: 9; lisp: 1
file content (62 lines) | stat: -rw-r--r-- 1,999 bytes parent folder | download | duplicates (6)
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
require "tempfile"

require "vagrant/util/shell_quote"

module VagrantPlugins
  module GuestLinux
    module Cap
      class PublicKey
        def self.insert_public_key(machine, contents)
          comm = machine.communicate
          contents = contents.strip << "\n"

          remote_path = "/tmp/vagrant-insert-pubkey-#{Time.now.to_i}"
          Tempfile.open("vagrant-linux-insert-public-key") do |f|
            f.binmode
            f.write(contents)
            f.fsync
            f.close
            comm.upload(f.path, remote_path)
          end

          # Use execute (not sudo) because we want to execute this as the SSH
          # user (which is "vagrant" by default).
          comm.execute <<-EOH.gsub(/^ */, "")
            mkdir -p ~/.ssh
            chmod 0700 ~/.ssh
            cat '#{remote_path}' >> ~/.ssh/authorized_keys && chmod 0600 ~/.ssh/authorized_keys
            result=$?
            rm -f '#{remote_path}'
            exit $result
          EOH
        end

        def self.remove_public_key(machine, contents)
          comm = machine.communicate
          contents = contents.strip << "\n"

          remote_path = "/tmp/vagrant-remove-pubkey-#{Time.now.to_i}"
          Tempfile.open("vagrant-linux-remove-public-key") do |f|
            f.binmode
            f.write(contents)
            f.fsync
            f.close
            comm.upload(f.path, remote_path)
          end

          # Use execute (not sudo) because we want to execute this as the SSH
          # user (which is "vagrant" by default).
          comm.execute <<-EOH.sub(/^ */, "")
            if test -f ~/.ssh/authorized_keys; then
              grep -v -x -f '#{remote_path}' ~/.ssh/authorized_keys > ~/.ssh/authorized_keys.tmp
              mv ~/.ssh/authorized_keys.tmp ~/.ssh/authorized_keys && chmod 0600 ~/.ssh/authorized_keys
              result=$?
            fi
            rm -f '#{remote_path}'
            exit $result
          EOH
        end
      end
    end
  end
end