Error using gem net/ssh <= Net::SSH::AuthenticationFailed - ruby

While using the gem net/ssh I'm getting the error:
/usr/local/lib/ruby/gems/1.9.1/gems/net-ssh-2.0.23/lib/net/ssh.rb:192:in
`start': Net::SSH::AuthenticationFailed (Net::SSH::AuthenticationFailed)
I don't really understand what's going on..? I've done my research and discovered this but it doesn't really answer my question..
Is there a specific reason why the authentication is failing? All I'm doing is sshing to different servers, is there something specific I need to change?
Source:
require 'rubygems'
require 'net/ssh'
require 'etc'
print "Enter password: "
system "stty -echo"
#password = gets.chomp
system "stty echo"
def logged_in(server)
cmd = `who`.gsub(/[ \t].*/,"").gsub(/\A.*\n/,'')
check = Net::SSH.start(#host, #username, :password => #password) do |ssh|
ssh.exec!(cmd)
end
end
#host = %w(server_names_here) do |server|
logged_in(server)
end
#username = Etc.getlogin
I thought it might be the wrong password so I tried entering the password with the echo "on" and I am entering the correct password, I also thought maybe it's not pulling my username so I used: #username = 'my_username' I am still receiving the same error
Edit:
Found the problem, it had to do with where the #username was placed

The problem had to do with where #username was placed.
require 'rubygems'
require 'net/ssh'
require 'etc'
print "Enter password: "
system "stty -echo"
#password = gets.chomp
system "stty echo"
#username = Etc.getlogin #<= YAY!
def logged_in(server)
cmd = `who`.gsub(/[ \t].*/,"").gsub(/\A.*\n/,'')
check = Net::SSH.start(#host, #username, :password => #password) do |ssh|
ssh.exec!(cmd)
end
end
#host = %w(server_names_here) do |server|
logged_in(server)
end

Related

Declaring Ruby Methods along with a menu

I've been fooling around with Ruby lately, so i decided to write an sftp client.
require 'net/sftp'
require 'ostruct'
require 'optparse'
class Sftp
def parse(arguments)
ARGV << "-h" if ARGV.empty?
#options = OpenStruct.new
args = OptionParser.new do |args|
args.banner = "Usage: #{__FILE__} [options]"
args.on("--host HOST", String,
) do |host|
#options.host = host
end
args.on("--username USERNAME", String,
) do |username|
#options.username = username
end
args.on("--password PASSWORD", String,
) do |password|
#options.password = password
end
args.on("--port=PORT", Integer,
) do |port|
#options.port = port
end
args.on("--mkdir=MAKE DIRECTORY", String,
) do |mkdir|
#options.mkdir = mkdir
end
args.on("--rmdir=REMOVE DIRECTORY", String,
) do |rmdir|
#options.rmdir = rmdir
end
args.on("-h", "--help", "Show help and exit") do
puts args
exit
end
end
begin
args.parse!(arguments)
rescue OptionParser::MissingArgument => error
puts "[!] ".red + error.message.bold
exit
rescue OptionParser::InvalidOption => error
puts "[!] ".red + error.message.bold
exit
end
def connect
Net::SFTP.start(#options.host, #options.username, :password => #options.password, :port => #options.port) do |sftp|
sftp.mkdir(#options.mkdir)
puts "Creating Directory: #{#options.mkdir}"
sftp.rmdir(#options.rmdir)
puts "Deleting Directory: #{#options.rmdir}"
end
end
end
def run(arguments)
parse(arguments)
connect
end
end
sftp = Sftp.new
sftp.run(ARGV)
I want these two commands to be separated. For example when i pass
the argument mkdir I just want only this to run and if I want to run rmdir again I just wanna run only this command.
It has to do with methods, but I can't find a proper solution. And I'm really rusty.
Any recommendation?
A very simple approach could be to check if the required value is set before running the command, and skip the command if the value is not set.
def connect
Net::SFTP.start(#options.host, #options.username, password: #options.password, port: #options.port) do |sftp|
if #options.mkdir
sftp.mkdir(#options.mkdir)
puts "Creating Directory: #{#options.mkdir}"
end
if #options.rmdir
sftp.rmdir(#options.rmdir)
puts "Deleting Directory: #{#options.rmdir}"
end
end
end

Remote server doesn't accept password, ruby script 'net/ssh'

I connect using ruby to the remote, pass the command, but channel.send_data ("passwd\n") dont work , I cant catch in than the reason. The password doesn't pass.
require 'rubygems'
require 'net/ssh'
...
Net::SSH.start(#hostname, #username, :password => #password) do |session|
stdout = ""
session.exec!(#cmd) do |channel, stream, data|
if data =~ /Password/
channel.send_data("passw\n")
end
stdout << data
end
puts stdout
session.close
end

Rspec for ssh connection

I am trying to write rspec to test ssh connection. In my spec file even though I have enetered incorrect server password it still says 0 examples, 0 failures. Can someone exmplain me why am I seeing that whereas I am expected to see at least one failure message.
Below is the piece of code of my ssh_host.rb and ssh_host_spec.rb files.
require "java"
require "highline/import"
require 'open-uri'
require 'socket'
require 'rubygems'
require 'net/ssh'
require 'stringio'
require 'net/scp'
require 'colorize'
module SshMod
class SshHost
attr_accessor :hostname, :username, :password
def initialize(host, user, password)
#hostname = host
#username = user
#password = password
#ssh = Net::SSH.start(#hostname, #username, :password => #password)
puts "\t Connection established for #{#hostname}...".blue
end
end
end
Rspec Class:
#!/usr/bin/env rspec
require 'spec_helper'
require 'ssh_host.rb'
describe SshMod::SshHost do
before :each do
#ssh = SshMod::SshHost.new "servername", "user", "wrong_password"
end
end
describe "#new" do
it "takes three parameters and returns sshhostobject" do
#ssh.should_be_an_instance_of SshHost
end
end
ssh_mock = double()
expect(SSH).to receive(:start).and_return(ssh_mock)
There are a number of things wrong with your spec file. your test for new should be within the context of your SshMod::SshHost describe otherwise it doesn't have access to the ssh instance variable. Also, your code should throw some errors because except isn't defined in Kernel it's within the context of an Rspec object. You most likely want to put it in your before.
Regarding your requires in your ruby class, I'd get rid of everything that you don't need (for example, why the explicit inclusion of socket when using net-ssh?).
I believe however, that you're running into the issue where no tests are running most likely due to your project structure (but that's only a guess since you haven't listed it). Rspec by default looks for spec files listed under spec/**/*_spec.rb which you can override with the --pattern flag. See rspec --help for more info.
Here's a working example of your code with a bunch of things cleaned up. I put the source of your code in lib assuming you're making something like a gem.
Gemfile:
source "https://rubygems.org"
gem "colorize"
gem "rspec"
gem "net-ssh"
lib/ssh_host.rb
require 'net/ssh'
require 'colorize'
module SshMod
class SshHost
attr_accessor :hostname, :username, :password
def initialize(host, user, password)
#hostname = host
#username = user
#password = password
#ssh = Net::SSH.start(#hostname, #username, password: #password)
puts "\t Connection established for #{#hostname}...".blue
end
end
end
spec/spec_helper.rb
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib')
require 'rspec'
RSpec.configure do |config|
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
spec/ssh_host_spec.rb
require 'spec_helper'
require 'ssh_host'
describe SshMod::SshHost do
let (:ssh) { SshMod::SshHost.new "servername", "user", "wrong_password" }
before :each do
allow(Net::SSH).to receive(:start).and_return(double("connection"))
end
describe "#new" do
it "takes three parameters and returns sshhostobject" do
expect(ssh).to be_a SshMod::SshHost
end
end
end

AuthenticationFailed net-ssh ruby

When I'm trying to Net::SSH.start to my debian ssh server and transfer a files, every time I've a very strange error message - `start': Net::SSH::AuthenticationFailed, but all the authentication data are correct, I don't know what a problem is. Does anyone faced same problem?
The code was written on ruby and net/ssh module are in use, here is a code:
require 'rubygems'
require 'net/ssh'
def copy_file(session, source_path, destination_path=nil)
destination_path ||= source_path
cmd = %{cat > "#{destination_path.gsub('"', '\"')}"}
session.process.popen3(cmd) do |i, o, e|
puts "Copying #{source_path} to #{destination_path}... "
open(source_path) { |f| i.write(f.read) }
puts 'Done.'
end
end
Net::SSH.start("192.168.112.129",
:username=>'username',
:password=>'password') do |session|
copy_file(session, 'D:/test/1.txt')
copy_file(session, '/home/timur/Documents/new_file.rb"')
end
There is no :username option in net/ssh 2.6, you can set it like parameter:
Net::SSH.start('192.168.112.129', 'username', password: 'password') do |ssh|
foo
end

Receiving errors when saving Tweets to a database using Sinatra

I'm using Sinatra, EventMachine, DataMapper, SQLite3 and the Twitter Stream API to capture and save tweets. When I run the application from my command line, it seems to continually fail at tweet 50. If I'm not saving the tweets, it can run seemingly forever.
Below is the app code to capture tweets with 'oscar' in them, which provided a very quick stream. Just enter your twitter username and password and run at the command line.
require 'rubygems'
require 'sinatra'
require 'em-http'
require 'json'
require 'dm-core'
require 'dm-migrations'
USERNAME = '<your twitter username>'
PASSWORD = '<your secret password>'
STREAMING_URL = 'http://stream.twitter.com/1/statuses/filter.json'
DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/db/development.db")
class Tweet
include DataMapper::Resource
property :id, Serial
property :tweet_id, String
property :username, String
property :avatar_url, String
property :text, Text
end
DataMapper.auto_upgrade!
get '/' do
#tweets = Tweet.all
erb :index
end
def rip_tweet(line)
#count += 1
tweet = Tweet.new :tweet_id => line['id'],
:username => line['user']['screen_name'],
:avatar_url => line['user']['profile_image_url'],
:text => line['text']
if tweet.save
puts #count
else
puts "F"
end
end
EM.schedule do
#count = 0
http = EM::HttpRequest.new(STREAMING_URL).get({
:head => {
'Authorization' => [ USERNAME, PASSWORD]
},
:query => {
'track' => 'oscars'
}
})
buffer = ""
http.stream do |chunk|
buffer += chunk
while line = buffer.slice!(/.+\r?\n/)
rip_tweet JSON.parse(line)
end
end
end
helpers do
alias_method :h, :escape_html
end
I'm not sure you can safely mix EM and Sinatra in the same process. You might want to try splitting the Sinatra viewer and the EventMachine downloader into separate programs and processes.

Resources