Skip to content

Instantly share code, notes, and snippets.

@pavanbuzz
Forked from estum/README.rdoc
Created March 26, 2017 11:23
Show Gist options
  • Save pavanbuzz/4454226ec57485b5f4667f1c60c0528d to your computer and use it in GitHub Desktop.
Save pavanbuzz/4454226ec57485b5f4667f1c60c0528d to your computer and use it in GitHub Desktop.
iTerm: Coprocess-script to auto-paste sudo password from keychain

iTerm Coprocess-script to auto-paste sudo password from keychain

Usage

  1. Open Keychain Access.app and create new object using the host as a name (“example.com”), username with sudo rights (“user”) and it’s password.

  2. Add a trigger for iTerm’s profile (‘Advanced‘ tab):

    • Regular Expression: \$ sudo

    • Action: Run Coprocess…

    • Parameters: /path/to/iterm_reply_with_keychain.rb user@example.com

#!/usr/bin/env ruby -rexpect
# minimum ruby version: <b>2.0</b>
module Iterm
# = Example usage:
#
# Run for example.com host, don't wait (default: wait 1 seconds), expect
# line contains "[sudo] password for somebody" (default: the same)
#
# Iterm::ReplyWithKeychain.("somebody@example.com", 0, "[sudo] password for %{user}")
#
# The same args from command line:
#
# ./iterm_reply_with_keychain.rb somebody@example.com
#
class ReplyWithKeychain
attr_accessor :user, :host, :expect_text, :expect_timeout
def self.call(*args)
new(*args).expect_and_auth
end
def initialize(uri, timeout = nil, pattern = "[sudo] password for %{user}")
@user, @host = uri.to_s.split "@"
@expect_timeout = (timeout || 5).to_i
@expect_text = format pattern, user: user, host: host
end
def expect_and_auth(delay: 1)
STDIN.expect expect_pattern, expect_timeout do |result|
if !result.nil? && result.any?
sleep(delay) if delay > 0
STDOUT.puts pass_from_keychain
end
end
end
private
def pass_from_keychain
`security find-generic-password -a #{user} -l #{host} -w`.to_s.chomp
end
def expect_pattern
Regexp.new Regexp.quote(expect_text)
end
end
end
Iterm::ReplyWithKeychain.(*ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment