require'open3'## Access username and password from mac os x keychain## Author: Thomas Flemming (thomasfl at usit dot uio dot no) 2009## synposis## read_password www.webdav.org# userame: tiger# password: scott## To add username and password to you keychain## 1. Go to a webpage protected with http(s) authentication# 2. Type in username and password, and check the# box for adding username and password to keychain# 3. Run this script.# 4. A Keychain dialog windows should appear. Click# on the button to allow access to the program "security".## User Keychain Access to remove privilegies, username or passwords# from keychain.#defdecode_hex_string(hex_str)
str =""
i =true
hex_str.split("").each do | char |
if(i)
str += char
i =falseelse
str += char +" "
i =trueendend
decoded_str =""
str.split(' ').each do |val|
decoded_str += val.hex.chr
endreturn decoded_str
enddeffetch_keychain_password(server)
command ="security find-internet-password -g -s "+ server
username =nil
password =nilOpen3.popen3(command) do |stdin, stdout, stderr|
stderr = stderr.readlines.join("")
stderr=~/^password: "(.*)"$/
password =$1if(!password)
stderr=~/^password: (0x.*)$/
password =$1if(password)
password = decode_hex_string( password.sub(/^0x/,"") )
endend
stdout = stdout.readlines.join("")
stdout =~/"acct"[^=]*="(.*)"/
username =$1endreturn [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