Ruby NET::SCP and custom ports - ruby

I'm trying to define a custom port for the ssh connection using Net::SCP, but without luck so far.
Here's an example how I'm trying to download a remote file from a server with a custom ssh port:
require "rubygems"
require 'net/scp'
Net::SCP.download!("www.server.com", "user", "/opt/platform/upload/projects/file.txt", "/tmp/bb.pdf",{:password => "mypassword",:port => 22202})
The error message I'm getting is:
Errno::ECONNREFUSED: Connection refused - connect(2)
There are no entries in the server logs regarding the ssh connection, so I assume that Net::SCP isn't using my custom port.
Any tips for me ?
Regards, Alex

Well, I've found the solution myself.
require "rubygems"
require "net/scp"
Net::SSH.start("www.myserver.com", "theuser", {:password => "whateverpwd",:port => 22212}) do |ssh|
ssh.scp.download! "/opt/platform/upload/projects/my.pdf", "/tmp/bb.pdf"
end

I also keep SSH on a non-standard port and use SCP like so:
Net::SCP.upload!( "foo.net", "user", the_file, the_file, :ssh => { :keys => #keys, :port => the_port } )
Works like a champ. I also use key-based authentication, hence the keys parameter getting passed along with the port.

Related

Enabling SSL for a thin server and sinatra

I'm trying to enable SSL for my thin server web app so that it can work over HTTPS.
I have done the following:-
launching of thin web server
MyApp.run! :host => '127.0.0.1', :port => 9090, :sslenable => true, :sslverifyclient => OpenSSL::SSL::VERIFY_NONE,
:sslcertificate => '.ssl/server_key.pem', :sslprivatekey => '.ssl/key.pem'
I generated a self signed certificate and private key using the openssl module in Ruby, created a directory called .ssl and stored them there as pem files.
The web framework I'm using for my web app is Sinatra. I'm also using the rack-ssl gem in the following way..
myapp.rb
require 'rack/ssl'
class MyApp < Sinatra ::Base
use Rack::SSL
use Rack::Session::Cookie,
:key => '_rack_session',
:path => '/',
:expire_after => 2592000,
:secret => ''
...
end
When I go to http://localhost:9090, I would expect to see my app displayed as normal but with a padlock and a cross through it as any http request is being redirected to https and I see the error "webpage is not available". However when I remove ssl-rack ruby gem and restart my app and go to https://localhost:9090,i get an ssl connection error with the following details:
Unable to make a secure connection to the server. This may be a problem with the server, or it may be requiring a client authentication certificate that you don't have.
Error code: ERR_SSL_PROTOCOL_ERROR
Can anyone please advise me on how best to configure a thin server to enable SSL?
I'm running Sinatra and Thin on Heroku with SSL using the Rack::SslEnforcer, doing this:
if production?
require 'rack/ssl-enforcer'
use Rack::SslEnforcer
end
This should be before you enable :sessions in your file. So, Rack::SslEnforcer needs to be placed above the session part when you configure your app.
Somewhat unrelated, but perhaps still relevant, you might consider adding:
require 'encrypted_cookie'
cookie_config = {
:key => 'usr',
:path => "/",
:expire_after => 86400, # one day in seconds
:secret => ENV["COOKIE_KEY"],
:httponly => true
}
cookie_config.merge!( :secure => true ) if production?
use Rack::Session::EncryptedCookie, cookie_config
You also need to set the COOKIE_KEY in your environment to something secret and long-ish.

Using gmail smtp via Laravel: Connection could not be established with host smtp.gmail.com [Connection timed out #110]

When I try to use GMail SMTP for sending email via Laravel, I encounter the following error:
Swift_TransportException
Connection could not be established with host smtp.gmail.com [Connection timed out #110]
It is the trace of the error:
...
}
$this->_stream = #stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options));
if (false === $this->_stream) {
throw new Swift_TransportException(
'Connection could not be established with host ' . $this->_params['host'] .
' [' . $errstr . ' #' . $errno . ']'...
and here are my configuration for mail:
'driver' => 'smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'from' => array('address' => 'some#example.ir', 'name' => 'some'),
'encryption' => 'tls',
'username' => 'myemail#gmail.com',
'password' => 'mypassword',
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false
I use a shared host and the port 587 on localhost is open.
I had the same problem and I resolved it in this way:
'driver' => 'sendmail',
You need to change only that line.
After doing lot of research I found this one helpful.
https://www.google.com/settings/security/lesssecureapps.
Open the above link .
Click on Enable. And save it.
Then try to send email again.
For me it worked .
Solved mine by changing my .env file as follows:
'driver' => 'sendmail',
Try
'encryption' => 'ssl',
'port' => 465,
The problem is that smtp.gmail.com is resolving an IPv6 address and that google service only listens on IPv4. What you need to do is set the source IP to ensure domains resolve as IPv4 and not IPv6.
The important method:
->setSourceIp('0.0.0.0')
How you might use it in code:
$this->_transport = Swift_SmtpTransport::newInstance
(
'smtp.gmail.com',
465,
'ssl'
)
->setUsername('username')
->setSourceIp('0.0.0.0')
->setPassword('password');
Works for me with same settings except encryption and port. Change to:
'encryption' => ssl,
'port' => 465,
Since this is only for localhost encryption line should also be environment specific. So instead above I did following:
env('MAIL_ENCRYPTION','tls'),
Now you can set this in .env file, which is environment specific and should be in .gitignore
I got the same problem using laravel forge + digitalocean.
I find when i try telnet smtp.gmail.com 465
telnet smtp.gmail.com 465
Trying 2404:6800:4003:c00::6d... # more than 30 sec
Trying 74.125.200.108... # less 1 sec
Connected to smtp.gmail.com.
Maybe is IPv6 that it Connection timed out.
So,I change gai.conf to prioritize ipv4 over ipv6
vi /etc/gai.conf
#For sites which prefer IPv4 connections change the last line to
precedence ::ffff:0:0/96 100
...
# For sites which use site-local IPv4 addresses behind NAT there is
# the problem that even if IPv4 addresses are preferred they do not
# have the same scope and are therefore not sorted first. To change
# this use only these rules:
#
scopev4 ::ffff:169.254.0.0/112 2
scopev4 ::ffff:127.0.0.0/104 2
scopev4 ::ffff:0.0.0.0/96 14
open your .env file and change this
MAIL_DRIVER=smtp
TO
MAIL_DRIVER=sendmail
this fixed my problem, hope it will help you as well.
The error might be due to 2 step verification enabled. In that case you need to create gmail app password and use this as password.
For me after trying all above solution the only thing that worked for my was
Disabling My Firewall and Antivirus temporarily
If it is a non-Google Apps account, definitely enable access from less secure apps as suggested. If you don't do that, it won't work.
If it is a Google Apps account (ie it's a business account) then there is an admin panel that governs access. You will need to make sure it is only specifying access by authentication and not by IP, since if it is by IP your IP presumably is not on the list.
The final thing to try is using the IPv4 address of smtp.gmail.com in place of that domain name in your code. I found that mine would not connect using the domain (because that resolved to an IPv6 address) but would connect when I used the raw IP in its place.
I got the same problem using Swiftmailer
Anyway, a quick dirty hack you should not use would be to edit swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php. In _establishSocketConnection() line 253 replace:
$options = array();
with something like this:
$options = array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false));
This will change the ssl options of stream_context_create() (a few lines below $options):
$this->_stream = #stream_socket_client($host.':'.$this->_params['port'], $errno,
$errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options));
There is a dirty hack for this You can find it here
Also my ENV is set to
MAIL_DRIVER=smtp
MAIL_HOST=mail.mydomain.com
MAIL_PORT=587
MAIL_USERNAME=noreply#mydomain.com
MAIL_PASSWORD=mypassword
In your terminal use this command
sudo ufw allow in "Postfix Submission"
this enable port 587 for SMTP
you need to create 2 factor auth and custom password in google account. Also don't forget to add custom password for every new host you are using.
For temporary fix you can resolved the issue by updating env file as 'driver' => 'sendmail'
Check your free disk space. On my case, I have 100% used.
I am using MAMP on MAC. I face this Issue Step to Follow to solve this problem on MAC
SMTP MAIL on MAC OS
Create a file to store our credentials:
sudo vim /etc/postfix/sasl_passwd
Add something like this:
smtp.gmail.com:587 username#gmail.com:password
Now run:
sudo postmap /etc/postfix/sasl_passwd
Prepare the postfix main config file:
sudo vim /etc/postfix/main.cf
Add/update these lines
relayhost=smtp.gmail.com:587
smtp_sasl_auth_enable=yes
smtp_sasl_password_maps=hash:/etc/postfix/sasl_passwd
smtp_use_tls=yes
smtp_tls_security_level=encrypt
tls_random_source=dev:/dev/urandom
smtp_sasl_security_options = noanonymous
smtp_always_send_ehlo = yes
smtp_sasl_mechanism_filter = plain
Stop/Start the service
sudo postfix stop
sudo postfix start
Check the queue for any errors
mailq
Your .env configuration should look like this
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME="username#gmail.com"
MAIL_PASSWORD="password"
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="username#gmail.com"
MAIL_FROM_NAME="${APP_NAME}"

cannot connect to Postgres (pg) database from my Ruby Script using gem "pg"(This is not rails, just pure ruby)

I downloaded the postgres.app for my Mac OSX machine. I have a rails app that has connected and used the postgres DB that came with the postgres app.
Now I am writing a pure Ruby test script (Not Rails, pure Ruby, not even Active Record) to try to connect to the postgres database instance. These are the steps I followed to set this up
1) ran this command on the terminal:
gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/MacOS/bin/pg_config
2) Added this code to the test script:
#!/usr/bin/env ruby
#encoding: utf-8
require "pg"
#conn = PG.connect(
:dbname => 'oData',
:user => 'am',
:password => '')
#conn.exec("CREATE TABLE programs (id serial NOT NULL, name character varying(255);");
I got this from this link
When I ran this script I get the following error:
/Users/am/.rvm/gems/ruby-2.0.0-p247/gems/pg-0.16.0/lib/pg.rb:38:in `initialize': could
not connect to server: No such file or directory (PG::ConnectionBad)
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
My Debug efforts:
My postgres.app is up and running.
I looked at the pg gem [documentation][2] and my syntax seemed OK.
The location of my postgres DB is entered in my bash script like so
PATH="/Applications/Postgres.app/Contents/MacOS/bin:$PATH"
Not sure what to do next. Any help would be appreciated, Thanks.
are you sure postgres is listening on a socket? are you sure the username and password is right?
I would be inclined to try something like
require 'pg'
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '')
puts "trying with tcp"
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '', :port => 5432)
I used active record gem to make the connection work and it was fine
Settings to connect works for me.
But that code should look like
#conn.exec("CREATE TABLE programs (id serial NOT NULL, name
character(255))")

Tiny_tds: Connect: Server name not found in the configuration files

require "rubygems"
require "tiny_tds"
client = TinyTds::Client.new(:username => 'sa', :password => '', :host => 'RICHARD_PC\SQLEXPRESS')
result = client.execute("SELECT * FROM [Contacts]")
result.each do |row|
//Do something
end
I keep getting the same error: "Connect: Server name not found in the configuration files". All I need to do is to be at least be able to connect with Sql Server. So if the host is not the sqlexpress instance installed on my machine, what is it then? In the Github website it said this host => 'mydb.host.net' (:host - Used if :dataserver blank. Can be an host name or IP.)
Thanks for helping.
Either use
:dataserver => 'RICHARD_PC\SQLEXPRESS'
Or use
:host => 'RICHARD_PC', :port => 1433
For those running rails on vagrant, I got this error when my vagrant network connections stopped working (mostly just the DNS), so a reboot fixed the issue.

Ruby Sinatra - connect to mongoDB on mongoHQ failed

This is just for my weekend project/study, I am very new to Sinatra and MongoDB.
I've installed the gems for mongoDB, such as: mongo, mongo_mapper and mongoid.
When I tried connecting to my database on MongoHQ from localhost, it encountered such an error:
Mongo::ConnectionFailure at /
failed to connect to any given host:port
* file: connection.rb
* location: connect
* line: 489
I found a similar thread on SO, but frankly speaking, I don't quite understand the answers...
Here is my code snippet:
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongo_mapper'
get '/' do
MongoMapper.connection = Mongo::Connection.new('flame.mongohq.com', 27044)
MongoMapper.database = 'notes'
MongoMapper.database.authenticate('foo', 'bar')
erb :list
end
I took the above code from here, but it seems not working...
Which part is wrong? Is there another way to do this? In the end this test web app will be deployed onto heroku, so I hope the solution can work with both localhost and my heroku server.
Updated:
I just created a minimal code snippet to test the mongodb connection:
require 'rubygems'
require 'mongo'
db = Mongo::Connection.new("flame.mongohq.com", 27044).db("notes")
But still got the error, after timeout:
$ ruby mongodbtest.rb
/Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:489:in
`connect': failed to connect to any given host:port (Mongo::ConnectionFailure)
from /Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:137:in
`initialize'
from mongodbtest.rb:4:in `new'
from mongodbtest.rb:4
The hostname and port are according to mongoHQ documentation, so they must be right.
Thanks for the help in advance.
2nd Update:
I just tested the mongodb connection string using terminal:
mongo mongodb://flame.mongohq.com:27044/notes -u foo -p bar
Unfortunately this would get me an connection failed error, honestly, I don't know why...
I use
uri = URI.parse(ENV['MONGOHQ_URL'])
#mongo_connection = Mongo::Connection.from_uri( uri )
#mongo_db = #mongo_connection.db(uri.path.gsub(/^\//, ''))
#mongo_db.authenticate(uri.user, uri.password)
You can look up your mongo url using the heroku config --long command
Just gave this another try, this time, I was using the ip address taken from ping:
So, if I change :
db = Mongo::Connection.new('flame.mongohq.com', 27060).db("notes")
db.authenticate('fake', 'info')
To:
db = Mongo::Connection.new('184.73.224.5', 27060).db("notes")
db.authenticate('fake', 'info')
That will work...
I still don't understand why the domain name approach won't work, but at least I can finish this off :)

Resources