require 'open3'
def decode_hex_string(hex_str)
str = ""
i = true
hex_str.split("").each do | char |
if(i)
str += char
i = false
else
str += char + " "
i = true
end
end
decoded_str = ""
str.split(' ').each do |val|
decoded_str += val.hex.chr
end
return decoded_str
end
def fetch_keychain_password(server)
command = "security find-internet-password -g -s " + server
username = nil
password = nil
Open3.popen3(command) do |stdin, stdout, stderr|
stderr = stderr.readlines.join("")
stderr=~ /^password: "(.*)"$/
password = $1
if(!password)
stderr=~ /^password: (0x.*)$/
password = $1
if(password)
password = decode_hex_string( password.sub(/^0x/,"") )
end
end
stdout = stdout.readlines.join("")
stdout =~ /"acct"[^=]*="(.*)"/
username = $1
end
return [username, password]
end
host = ARGV[0]
if(!host)
puts "read_password: error: missing hostname"
puts "read_password: usage read_password hostname"
exit
end
result = fetch_keychain_password(host)
if(result[0])
puts "Username:" + result[0]
puts "Password:" + result[1]
else
puts "Username and password not set for " + host
puts "[Instructions for adding username and password for "
puts "to server with Safari and Keychain...]"
end