Lucy Bain
Lucy Bain

Reputation: 2616

How can I get the output of an ssh command?

I'd like to programmatically check if someone has their SSH keys set up correctly for GitHub. I understand that I can use `ssh -T [email protected]` in Ruby. However, I'd like to keep the ssh output in a variable.

My current code is:

github_response = `ssh -T [email protected]`
unless github_response.start_with?('Hi')
  puts 'Please set up your GitHub ssh keys'
end

`ssh -T [email protected]` outputs the response (starting with "Hi"). However the github_response variable is nil.

How can I assign the output of `ssh -T [email protected]` to github_response?

Upvotes: 1

Views: 195

Answers (2)

halfelf
halfelf

Reputation: 10107

Your example failed because the Hi xxx! You've successfully authenticated.... message is not from stdout, but stderr.

> require 'open3'
=> true
> stdin, stdout, stderr, wait_thr = Open3.popen3('ssh -T [email protected]')
=> [#<IO:fd 8>, #<IO:fd 9>, #<IO:fd 11>, #<Thread:0x007f89ee1149a8 sleep>]

> stdout.gets
=> nil
> stderr.gets
=> "Hi halfelf! You've successfully authenticated, but GitHub does not provide shell access.\n"

Upvotes: 3

user3747345
user3747345

Reputation: 408

You could add -v for verbose output, it will then dump much of the connection info to stdout. From that log you can scrape to find whether the server accepted any of the keys the ssh client offered

Upvotes: 1

Related Questions