How to connect to mongo, using ruby that have credentials? - ruby

I am trying to connect to a database that has credentials. I cannot find any useful information online...
require: 'mongo'
begin
db = Mongo::Connection.new(" IP ADDRESS " , PORT ).db("COLLECTION")
db.authenticate("username","password")
rescue StandardError => err
abort("error")
end
C:/Ruby193/lib/ruby/gems/1.9.1/gems/mongo-1.8.2/lib/mongo/networking.rb:306:in `rescue in receive_message_on_socket': Operation failed with the following exception: end of file reached (Mongo::ConnectionFailure)

looks like there is an #add_auth method as well as auths can be passed to the constructor maybe try
auths = [{"db_name" => "COLLECTION",
"username" => YOUR_USERNAME,
"password" => YOUR_PASSWORD}]
Mongo::Connection.new(" IP ADDRESS " , PORT, auths: auths)
OR
auth = {"db_name" => "COLLECTION",
"username" => YOUR_USERNAME,
"password" => YOUR_PASSWORD}
Mongo::Connection.new(" IP ADDRESS " , PORT).add_auth(auth)
and see if that works
Reference Mongo::MongoClient::GENERIC_OPTS and Mongo::MongoClient#setup
BTW that is a old version of the gem and ruby for that matter. have you considered the possibly upgrading?
Newest version (as of now) of Mongo is 2.4.3 and the options are more transparent now e.g.
Mongo::Client.new("IP_ADDRESS:PORT", user: USERNAME, password: PASSWORD, auth_mech: AUTHENTICATION_MECHANISM)
Although based on your comments I am not sure authentication is your issue

Related

Puppet provider prefetch

I am writing a provider to generate self signed certificate using the certdog krestfield API.
I have implemented the create, destroy, exists? method and I can properly manage my certificate by making different call to the API.
I implemented puppet resource using the self.prefetch and self.instances methods. I can retrieve the properties of my resources to be aware of their current state.
My resource contain two sensitive types 'username' and 'password' who are required to make the API calls. I can't store those values on the filesystem and I want the 'puppet resource' command to ignore those types.
Currently when I run 'puppet apply' for the manifest:
certdog_certificate { 'tstpuppet':
ensure => present,
server => 'apiserver',
username => 'apiserver_username',
password => 'apiserver_password',
}
It returns:
Notice: /Stage[main]/Main/Certdog_certificate[tstpuppet]/username: defined 'username' as 'apiserver_username'
Notice: /Stage[main]/Main/Certdog_certificate[tstpuppet]/password: defined 'password' as 'apiserver_password'
Is there a way to hide sensitive types for puppet resources ? How should I process ?
I had to properly define my resource attributes.
The configurable data not part of the persistant state should be parameters as describe in the puppet documentation.
The attributes username and password are now define with newparam instead of newproperty as below.
module Puppet
Type.newtype(:certdog_certificate) do
#doc = 'Manage certificate using certdog REST API'
ensurable do
desc 'Create or remove a certificate'
newvalue(:present) do
provider.create
end
newvalue(:absent) do
provider.destroy
end
defaultto :present
end
newparam(:cert_name, namevar: true) do
desc 'Name of the certificate request'
end
newparam(:username) do
desc 'Username for Certdog API server'
end
newparam(:password) do
desc 'Password for Certdog API server'
end
newproperty(:server) do
desc 'Certdog API server address'
end
end
#john-bollinger Thanks for your explanation, I was missing an important concept of the custom types.

send email via telnet ruby script

I'm new with ruby and need to send an email via telnet using a relay host with no authentication. I can do it with a linux shell but I need to put it in a script so I can "simplify" its use, I know it's not the best way but I can't find other since the server where i'm working on it's severely restricted and limited.
require 'net/telnet.rb'
mail = Net::Telnet::new(
"Host" => "domain.ip", # default: "localhost"
"Port" => 25, # default: 23
"Output_log" => "output_log", # default: nil (no output)
"Dump_log" => "dump_log", # default: nil (no output)
"Prompt" => /[$%#>] \z/n, # default: /[$%#>] \z/n
"Telnetmode" => true, # default: true
"Timeout" => 10, # default: 10
"Waittime" => 0, # default: 0
)
mail.cmd('helo MYDOMAIN'){ |c| print c }
mail.cmd('mail from: test#domain.com')
mail.cmd('rcpt to: test2#domain.com')
mail.cmd('data')
mail.cmd("subject: test cmd \n\n mensaje de prueba\n\n")
mail.cmd(".\n")
mail.close
I found the net/telnet.rb ruby class and this is my try... after mail.cmd('helo MYDOMAIN') I can't keep writing other commands, what I get is:
220 mail.server.com ESMTP
250 mail.server.com
After this I'm suposed to write mail from, etc. to create the mail. But I can't in the ruby script. I have try using:
mail.puts('mail from: test...')
mail.write('mail from: test...')
mail.print('mail from: test...')
mail.cmd('mail from: test...')
As written in documentation
Also I don't get the telnetmode(true|false) command maybe you could explain it to me please.
-- Edit --
Shell code trying to emulate:
telnet domain.ip 25
#=> Trying domain.ip...
#=> Connected to domain.ip.
#=> Escape character is '^]'.
#=> 220 mail.server.com ESMTP
helo MYDOMAIN
#=>250 mail.server.com
mail from:test#mydomain.com
#=> 250 2.1.0 Ok
rcpt to:test2#mydomain.com
#=> 250 2.1.0 Ok
data
#=> 354 End data with <CR><LF>.<CR><LF>
subject: test mail
test mail body
.
#=> 250 2.0.0 =k: queued as B6F08480D12
quit
#=> 221 2.0.0 Bye
#=> Connection closed by foreign host.
The telnet protocol is really, really rudimentary which is why the telnet command is useful for testing TCP/IP based services such as SMTP or HTTP. It does not mean those services actually use the telnet protocol, as they don't. They're conveniently plain-text in nature which means it's practical to use telnet for simple tests.
You should not be using the Telnet module for anything other than connecting to telnet services, though given it's 2017 it's unlikely you'll find any of those around.
You should be using something like Socket to connect. This can create a bare TCP/IP connection with full control over sending. As this is a wrapper around a regular POSIX filehandle you can use all the IO methods on it for reading, writing, and other control functions, like a proper socket shutdown.
Writing an SMTP adapter is not as easy as it seems, there's a lot of tricky things to tackle with regard to IO. You'll need to use IO.select to properly test for new data, plus that the socket is clear to write your email.
Here's a new stub:
require 'socket'
mail = TCPSocket.new("smtp.example.com", 25)
mail.write("HELO example.com\r\n")
Another note is that when you call require you should never specify the file extension. It's always handled for you.
Thanks to the help of the user ddubs how suggest the net\smtp gem (One that I didn't know) I was able to create a simple mail sender and using the mailfactory gem
Is it a strict requirement that you use telnet? Using ruby-doc.org/stdlib-2.0.0/libdoc/net/smtp/rdoc/Net/SMTP.html will turn your "difficult to maintain" script into something that is much easier to maintain. Even for someone who is completely new to Ruby. – ddubs
Here is the code sample
require 'net/smtp'
require 'mailfactory'
mail_body_HTML = '<h1> mail title</h1> your text in <b>HTML</b>'
mail_body_PLAIN = 'this is plain text'
mail_subject = 'test email'
mail_from = 'noreply#mydomain.com'
mail_to = 'user#otherdomain.com'
# mail_filePath = ''
mail = MailFactory.new()
mail.to = mail_to
mail.from = mail_from
mail.subject = mail_subject
mail.html = mail_body_HTML
# mail.text = mail_body_PLAIN
# mail.attach(mail_filePath)
relay_ip = x.x.x.x
Net::SMTP.start(relay_ip,25) do |smtp|
smtp.send_message(mail.to_s, mail_from, mail_to)
end

Ruby hipchat gem invalid send file

So this is related to an earlier post I made on this method. This is essentially what I am using to send files via hipchat:
#!/usr/bin/env ruby
require 'hipchat'
client = HipChat::Client.new('HIPCHAT_TOKEN', :api_version => 'v2', :server_url => 'HIPCHAT_URL')
client.user('some_username').send_file('message', File.open('./output/some-file.csv') )
client['some_hipchat_room'].send_file('some_user', 'message', File.open('./output/some-file.csv') )
Now for some reason the send_file method is invalid:
/path/to/gems/hipchat-1.5.4/lib/hipchat/errors.rb:40:in `response_code_to_exception_for': You requested an invalid method. path:https://hipchat.illum.io/v2/user/myuser#myemail/share/file?auth_token=asdfgibberishasdf method:Net::HTTP::Get (HipChat::MethodNotAllowed)
from /path/to/gems/gems/hipchat-1.5.4/lib/hipchat/user.rb:50:in `send_file'
I think this indicating that you should be using POST instead of GET, but I'm not sure because I haven't used this library nor Hipchat.
Looking at the question you referenced and the source posted by another user they're sending the request using self.class.post, and your debug output shows Net::HTTP::Get
To debug, could you try,
file = Tempfile.new('foo').tap do |f|
f.write("the content")
f.rewind
end
user = client.user(some_username)
user.send_file('some bytes', file)
The issue is that I was attempting to connect to the server via http instead of https. If the following client is causing issues:
client = HipChat::Client.new('HIPCHAT_TOKEN', :api_version => 'v2', :server_url => 'my.company.com')
Then try adding https:// to the beginning of your company's name.
client = HipChat::Client.new('HIPCHAT_TOKEN', :api_version => 'v2', :server_url => 'https://my.company.com')

sharepoint upload files by ruby

I want to upload files into "Share Documents" by ruby script.
I tried "savon" to link sparepoint but it can't succeed.
" WSDL = "http://xxx.xx.com/sites/OK/Shared%20Documents" " is right?
" client.request.basic_auth "user", "userpasd" "
And it show a error message
'request': Savon::Client#request requires at least one argument (ArgumentError)
How to fix it and how to link/upload/download file from sharepoint by ruby script?
Thanks a lot,
I was having this same problem and found the answer via google - https://groups.google.com/forum/#!msg/savonrb/gq90FDuu77s/H7ip3VNnt0MJ
The provided answer:
client = Savon::Client.new do
wsdl.document = File.expand_path('../../../lib/wsdl/MI_TESTConnection_OutHTTP.wsdl', __FILE__)
http.auth.basic "user", "password"
end
This is the actual code that worked for me:
client = Savon.client("http://path.to.my/service.wsdl") do
http.auth.basic "user", "password"
end

cannot create wall posts with fb_graph

i am attempting to create a test user, and then write on that user's
wall. here is my code followed by the error i get (i'm using ruby and the gem fb_graph):
app = FbGraph::Application.new(config[:client_id], :secret =>
config[:client_secret])
user1 = app.test_user!(:installed => true, :permissions
=> :publish_stream)
user2 = app.test_user!(:installed => true, :permissions
=> :publish_stream)
me = FbGraph::User.me(ACCESS_TOKEN)
me.feed!(:message => "Testing")
FbGraph::Unauthorized: FbGraph::Unauthorized from /Library/Ruby/Gems/
1.8/gems/fb_graph-1.9.4/lib/fb_graph/node.rb:126:in
'handle_httpclient_error'
from /Library/Ruby/Gems/1.8/gems/fb_graph-1.9.4/lib/fb_graph/node.rb:
115:in 'handle_response'
from /Library/Ruby/Gems/1.8/gems/fb_graph-1.9.4/lib/fb_graph/node.rb:
48:in 'post'
from /Library/Ruby/Gems/1.8/gems/fb_graph-1.9.4/lib/fb_graph/
connections/feed.rb:15:in `feed!'
from (irb):90
publish_stream should give me the proper permissions to write to the
wall, but as you can see, it doesn't.
any suggestions?
thanks for any help.
Are you sure your access token is valid? Facebook needs a valid access token or it will not allow you to use the user's permissions, even if he granted them to you on facebook.

Resources