   defp parse_output(nil), do: ""
   defp parse_output(out) do
     String.trim_trailing(out)
-  end    
+  end  
+
+  defp ssh_opts(user, nil), do: Keyword.merge(default_opts(), [user: user])
+  
+  defp ssh_opts(user, identity_file) do
+    case File.open(identity_file) do
+      {:ok, identity} ->
+        key_cb = ClientKeyAPI.with_options(identity: identity, accept_hosts: true)  
+        Keyword.merge(default_opts(), [user: user, key_cb: key_cb])
+      {_, msg} -> raise "Error: #{msg}"
+    end
+  end  
+
+  defp default_opts do
+    [ 
+      connect_timeout: 5000,       
+    ]
+  end
 end
  alias SSHKit.SCP
  
  def start, do: :ssh.start()

  def connect(host, user, identity_file) do
    with {:ok, identity} <- File.open(identity_file),
      cb = ClientKeyAPI.with_options(identity: identity),
      {:ok, conn} <- SSHKit.SSH.connect(host, [connect_timeout: 5000, key_cb: cb, user: user]) do
      conn
    else
      {_, msg} -> raise "Error: #{msg}"
    end
  end

  def run!(conn, cmd, working_directory) do
    case run(conn, build_cmd(cmd, working_directory)) do      
      {:ok, output, 0} -> {:ok, output}
      {:ok, output, status} -> raise format_error(cmd, output, status)
    end
  end

