Ruby: gem win32-service: Create a service with Admin privileges - ruby

I am using the win32-service gem to create a Windows service using Ruby (1.9.3-p429, MRI).
This snippet of code works.
require 'rubygems'
require 'win32/service'
include Win32
SERVICE_NAME = 'myservice'
# Create a new service
Service.create({
:service_name => SERVICE_NAME,
:service_type => Service::WIN32_OWN_PROCESS,
:description => 'A custom service I wrote just for fun',
:start_type => Service::AUTO_START,
:error_control => Service::ERROR_NORMAL,
:binary_path_name => 'c:\Ruby193\bin\ruby.exe -C c:\ c:\myservice.rb',
:load_order_group => 'Network',
#:service_start_name => 'Administrator',
#:password => 'adminpasswd',
:display_name => SERVICE_NAME
})
Service.start SERVICE_NAME
The problem I have is that the service needs to run with Administrator privileges, but the entity which calls this code snippet runs as the Local System Account, and that is the default privilege.
I can open up up the Services GUI (services.msc) and go in and stop the service, raise the privileges via the "Log On" tab of the service (myservice) properties, and use Administrator/adminpasswd as the user/password. It then runs the service with sufficient privileges.
However, when I try to call Service.create with the :service_start_name and :password set to exactly the same values (by uncommenting the lines in the code snippet) as I used in the Services tab, it doesn't work. This server is an Amazon EC2 server running Windows 2008r2 Datacenter Edition and is not a part of any Windows domain that I know of (because I started it).
What do I need to do differently to get this Windows service running with Administrator privileges?

The underlying CreateService Windows API function requires an account domain on the lpServiceStartName field, so you probably need to set the :service_start_name field to 'domain\Administrator', where the account domain is usually the computer name.

Borodin gave me a clue for this answer. When I went back to the Services GUI to reconfigure the service, I noticed that although I had typed 'Administrator' as the user name, the user name which actually showed up in the panel was '.\Administrator'. Keeping Borodin's comment in mind, it looks like I could specify '.' as the domain.
So...the code which actually worked was:
require 'rubygems'
require 'win32/service'
include Win32
SERVICE_NAME = 'myservice'
# Create a new service
Service.create({
:service_name => SERVICE_NAME,
:service_type => Service::WIN32_OWN_PROCESS,
:description => 'A custom service I wrote just for fun',
:start_type => Service::AUTO_START,
:error_control => Service::ERROR_NORMAL,
:binary_path_name => 'c:\Ruby193\bin\ruby.exe -C c:\ c:\myservice.rb',
:load_order_group => 'Network',
:service_start_name => '.\Administrator',
:password => 'adminpasswd',
:display_name => SERVICE_NAME
})
Service.start SERVICE_NAME

Related

Puppet does not honor 'require' modules

I have created a module to add a user as follows:
user { 'test':
ensure => 'present',
comment => 'Test User',
home => '/home/test',
shell => '/bin/bash',
managehome => 'true',
gid => 'postgres',
groups => 'users',
password => '$1$PIp.c9J6$gdAyd76OhBk7n9asda80wm0',
require => [ Package['rubygem-ruby-shadow'], Class['postgres'] ],
}
It requires the class postgres as I need its primary group to be assigned to postgres, and the rubygem-ruby-shadow dependency is for the password setup.
My problem is puppet does not honor these requirements. Puppet will always execute the useradd module first before rubygem-ruby-shadow, and this causes the password setup to fail. I have also tried to include rubygem-ruby-shadow in the same class as useradd but to no avail.
The output upon running puppet agent -t:
linux-z14x:~ # puppet agent -t
info: Caching catalog for linux-z14x.playground.local
info: /User[test]: Provider useradd does not support features manages_passwords; not managing attribute password
info: Applying configuration version '1425978163'
notice: /Stage[main]/Users/Package[rubygem-ruby-shadow]/ensure: created
notice: /User[test]/ensure: created
notice: Finished catalog run in 78.19 seconds
Running it the second time:
linux-z14x:~ # puppet agent -t
info: Caching catalog for linux-z14x.playground.local
info: Applying configuration version '1425978163'
notice: /Stage[main]/Users/User[test]/password: changed password
notice: Finished catalog run in 74.79 seconds
My rubygem-ruby-shadow class:
package { 'rubygem-ruby-shadow':
ensure => 'installed',
require => Class['myrepo'],
provider => 'zypper',
}
How do I get rubygem-ruby-shadow module to run first before the useradd?
Puppet master version is 3.7.4-1 (on CentOS) and puppet client is 2.6.12-0.10.1 (on SLES 11 SP2).
Thanks.
This is unfortunate. The provider detects the absence of ruby-shadow during agent initialization, and does not update its capabilities during the transaction.
This may be limitation of Puppet that might be fixed in a more recent version (what are you using?)
I do try and make sure to provide ruby-shadow along with Puppet itself everywhere, to avoid this very issue.

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))")

Chef : Create a process as another user

So I have some code for running a batch file as a specific user. This was my attempt to automate the following syntax
runas /user:thisguy "C:\ThisGuysScript.bat"
so it looks like this in Ruby
Process.create(:command_line => "C:\\ThisGuysScript.bat ", :domain => "MYServer", :with_logon => "thisguy", :password => "thisguyspassword", :cwd =>"C:\\")
So I try to put this in a recipe in chef and disaster strikes
require 'win32/process'
::Process.create(:command_line => "C:\\ThisGuysScript.bat ", :domain => "MYServer", :with_logon => "thisguy", :password => "thisguyspassword", :cwd =>"C:\\")
Is failing with the following error
[Tue, 30 Oct 2012 15:57:03 +0000] FATAL: ArgumentError: You must supply a name when declaring a user resource
So it seems to not realise that I want to use the win32 flavour process. Chef seems to override the win32 module (I know recipes are the opscode DSL rather than really ruby right?)
Anyone been able to get this working? Or the same function with a different implementation. Checked out the windows cookbook but didn't spot much
It sounds like you want to make an LWRP for creating a process on a windows machine.
The error you are getting means you have something like
user do # Missing name
gid 500
home "..."
end
the correct syntax is
user "apache" do # or whatever the user name should be
# ...
end
If you don't have the above in your cookbook, it is possible that the included file has a variable named user which would also cause this issue.
To answer your subquestion, Chef is straight ruby with some functions made available and a frame work to run things. Note, there are several stages in a chef run. I think you are having issues in the compilation stage.
Making an LWRP seems like the way to go. If you don't want to go that far you could do something like.
ruby_block "Firing process lazers" do
require 'win32/process'
::Process.create(:command_line => "C:\\ThisGuysScript.bat ", :domain => "MYServer", :with_logon => "thisguy", :password => "thisguyspassword", :cwd =>"C:\\")
end

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.

Sending mails automatically through action mailer Rails 3.1

I have to send weekly emails to all the user about the latest things happening. I am using ActionMailer to accomplish other mailing task however I have no clue how to automate the weekly emails.
Update
I found whenever gem which could be used to schedule cron jobs. I guess this could be used to send weekly emails which I intend to. Still looking how to make it work with ActionMailer will update once I find the solution
Update 2
This is what I have done so far using whenever gem:-
in schedule.rb
every 1.minute do
runner "User.weekly_update", :environment => 'development'
end
in users_mailer.rb
def weekly_mail(email)
mail(:to => email, :subject => "Weekly email from footyaddicts")
end
in users.rb
def self.weekly_update
#user = User.all
#user.each do |u|
UsersMailer.weekly_mail(u.email).deliver
end
end
If i try to run User.weekly_update from the console I am able to get the mails. I am testing in development mode and using rvm. I checked my crontab file and it has got the right stuff.
However I am not getting any mails automatically from the app. Any clue what might be wrong?
Thanks,
OK so it turns out to be a path issue with whenever gem, and the problem was created when I installed another version of ruby.
In my machine the new ruby version is installed in /usr/local/bin/ruby. In my rails app I had to go to the file script/rails and replace #!/usr/bin/env ruby with #!/usr/local/bin/ruby.
I found this out by visiting cron.log file which showed this error message :- /usr/bin/env: ruby: No such file or directory
I made a cron.log file to log the cron error this is what I did in my schedule.rb code written in the question :-
every 2.minutes do
runner "User.weekly_update", :environment => 'development', :output => 'log/cron.log'
end
I am getting periodic mails now.
It seems like you haven't configured ActionMailer settings.
First check out the logs from console, whether the mailing process is working(paste your logs).
If yes then do following steps.
add this in your gemfile.
gem 'tlsmail'
run
bundle install
write these configuration setting in your config/environments/development.rb file
require 'tlsmail'
Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => "587",
:domain => "gmail.com",
:enable_starttls_auto => true,
:authentication => :login,
:user_name => "<address>#gmail.com",
:password => "<password>"
}
config.action_mailer.raise_delivery_errors = true
add your working password/email against user_name and password.
Don't forget to restart server.

Resources