-
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.
-
Add a trigger for iTerm’s profile (‘Advanced‘ tab):
-
Regular Expression:
\$ sudo
-
Action: Run Coprocess…
-
Parameters:
/path/to/iterm_reply_with_keychain.rb [email protected]
-
Last active
August 23, 2023 13:47
-
-
Save estum/d73a8a86fae0bafd8459 to your computer and use it in GitHub Desktop.
iTerm: Coprocess-script to auto-paste sudo password from keychain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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.("[email protected]", 0, "[sudo] password for %{user}") | |
# | |
# The same args from command line: | |
# | |
# ./iterm_reply_with_keychain.rb [email protected] | |
# | |
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