I'm trying to write a JIRA-ruby script (only be used from command-line) to mark some JIRA issue closed automatically.
I borrow an example from here because I'm using 'jira-ruby' gem.
This works however it will pop-up a browser asking you to click "Allow" to get the access_token. I would like to do this programmatically, but I don't think the API was built for this purpose. As access_token changes every time, and this script will run periodically in a cronjob, so we need to have a way to do this. Any idea what other ways we can do this?
require 'jira'
#jira = JIRA::Client.new({:site => 'http://localhost:2990', :context_path => '/jira', :consumer_key => 'test-jira', :private_key_file => "rsakey.pem"})
if ARGV.length == 0
# If not passed any command line arguments, open a browser and prompt the
# user for the OAuth verifier.
request_token = #jira.request_token
puts "Opening #{request_token.authorize_url}"
system "open #{request_token.authorize_url}"
puts "Enter the oauth_verifier: "
oauth_verifier = gets.strip
access_token = #jira.init_access_token(:oauth_verifier => oauth_verifier)
puts "Access token: #{access_token.token} secret: #{access_token.secret}"
elsif ARGV.length == 2
# Otherwise assume the arguments are a previous access token and secret.
access_token = #jira.set_access_token(ARGV[0], ARGV[1])
else
# Script must be passed 0 or 2 arguments
raise "Usage: #{$0} [ token secret ]"
end
# Show all projects
projects = #jira.Project.all
projects.each do |project|
puts "Project -> key: #{project.key}, name: #{project.name}"
end
issue = #jira.Issue.find('DEMO-1')
puts issue
I know there's a way to use long-life access tokens, but not really use if Jira supports it.
I was using the jira-ruby gem at first but I found the performance terrible. I ended up just going with curl instead as I only needed to require the JSON gem which is less bloated. Have your Jira administrators create a user that will never have the password change with admin access and then do the following to find "DEMO-1"
require 'json'
username = "admin"
password = "abc123"
issue = JSON.parse(%x[curl -u #{username}:#{password} \"http://jira/rest/api/latest/issue/DEMO-1\"])
Here is a link to the Jira REST API documentation, just choose the same version of Jira you are using. This will bypass any issues with oauth and the pop-up.
Related
In my project I want to write a script to check if every device in my network is online/reachable. I have a method called pingtest and it works for now..
def pingtest(destination)
system("ping -n 2 #{destination}")
if $? == 0 #checking status of the backtick
puts "\n Ping was successful!"
else
close("Device is unreachable. Check the config.txt for the correct IPs.")
#close() is just print & exit..
end
end
Now I wanted to ping via a ssh session with an other device in my network:
#--------------------------------
require 'net/ssh'
Net::SSH.start(#ip, #user, :password => #password)
#--------------------------------
#ssh = Ssh.new(#config)
#ssh.cmd("ping -c 3 #{#IP}")
The ping works fine but how can I use my backtrack idea now to determine if it was succesful or not?
I thought about using a sftp connection..
"ping -c 3 #{#IP} => tmpfile.txt" => download => check/compare => delete
(or something like that) to check if it was correct, but im not statusfied with that. Is there a possibility to check the success status like I did before?
I also tried something like this..
result = #ssh.cmd("ping -c 3 #{#IP}")
if result.success? == 0 # and so on..
I startet learning ruby some days ago, so im a newbie looking forward for your ideas to help me with this problem.
You can use Net::SSH to run the command remotely, similarly to what you've already got there.
The result returned from running the command will be whatever is written to both stdout and stderr.
You can use the contents of that returned value to check if it was successful or not.
Net::SSH.start(#ip, #user. password: #password) do |ssh|
response = ssh.exec! "ping -c 3 #{#other_ip}"
if response.include? 'Destination Host Unreachable'
close("Host unreachable. Result was: #{result}")
else
puts "\n Ping was successful"
end
end
I am trying to get to grips with Cucumbers After Hooks and would like to run a hook after every tag in a feature. So for example within my feature login.feature I have multiple scenarios, each with their own tag
Feature: Login to myApp with various Users
#login_user_1
Scenario: Load Login Screen for User_1
Given I am on the login page
Then I will enter my credentials
Then I will successfully Login
Then I should Logout
#login_user_2
Scenario: Load Login Screen for User_2
Given I am on the login page
Then I will enter my credentials
Then I will successfully Login
Then I should Logout
My after hook consists of creating a screenshot for each scenario that fails, but at the moment only the last scenario in my feature is outputting a failure in the console, though images for both failed scenarios are created
After do |scenario|
dir_path = "/var/apps/MyApp/report/screenshots"
#Check scenario has failed?
if(scenario.failed?)
time = Time.now.strftime('%Y_%m_%d_%Y_%H_%M_%S_')
name_of_scenario = time + scenario.name.gsub(/\s+/, "_").gsub("/","_")
puts "#===========================================================#"
puts "TEST FAILED - Name of screenshot is #{name_of_scenario}"
puts "#===========================================================#"
file_path = File.expand_path(dir_path)+'/'+name_of_scenario +'.png'
page.driver.browser.save_screenshot file_path
end
end
The output i get at the moment is
Feature: Login to MyApp as various Users
#login_user_1
Scenario: Load Login Screen for user_1 # features/login.feature:4
Given I am on the login page # features/step_definitions/login.rb:1
expected to find css "#lnlogop" but there were no matches (RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/login.rb:3:in `/^I am on the login page$/'
features/login.feature:5:in `Given I am on the login page'
Then I will enter my credentials # features/step_definitions/login.rb:6
Then I will successfully Login # features/step_definitions/login.rb:13
Then I should Logout # features/step_definitions/login.rb:17
#login_user_2
Scenario: Load Login Screen for user_2 # features/login.feature:11
Given I am on the login page # features/step_definitions/login.rb:1
#===========================================================#
TEST FAILED - Name of screenshot is 2015_02_13_2015_11_15_02_Load_Login_Screen_for_MAuser
#===========================================================#
expected to find css "#lnlogop" but there were no matches (RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/login.rb:3:in `/^I am on the login page$/'
features/login.feature:12:in `Given I am on the login page'
Then I will enter my credentials # features/step_definitions/login.rb:6
Then I will successfully Login # features/step_definitions/login.rb:13
Then I should Logout # features/step_definitions/login.rb:17
Failing Scenarios:
cucumber features/login.feature:4 # Scenario: Load Login Screen for user_1
cucumber features/login.feature:11 # Scenario: Load Login Screen for user_2
What I want to achieve is have output in the console so that I know which scenario has failed.
Around Hooks
I looked into Around Hooks, and found that i could achieve this but no screenshot was being produced
Around('#user_1', '#user_2') do |scenario, block|
block.call
#Check scenario has failed?
if(scenario.failed?)
dir_path = "/var/apps/MyApp/report/screenshots"
time = Time.now.strftime('%Y_%m_%d_%Y_%H_%M_%S_')
name_of_scenario = time + scenario.name.gsub(/\s+/, "_").gsub("/","_")
puts "#===========================================================#"
puts "TEST FAILED - Name of screenshot is #{name_of_scenario}"
puts "#===========================================================#"
file_path = File.expand_path(dir_path)+'/'+name_of_scenario +'.png'
page.driver.browser.save_screenshot file_path
end
end
How can i output a failure message per scenario and get it to create the file
Thanks
Cucumber takes control of all puts messages so it can pass it along to all the formatters.
In the After hook try STDOUT.puts instead
I'd like to scrape the discussion list of a private google group. It's a multi-page list and I might have to this later again so scripting sounds like the way to go.
Since this is a private group, I need to login in my google account first.
Unfortunately I can't manage to login using wget or ruby Net::HTTP. Surprisingly google groups is not accessible with the Client Login interface, so all the code samples are useless.
My ruby script is embedded at the end of the post. The response to the authentication query is a 200-OK but no cookies in the response headers and the body contains the message "Your browser's cookie functionality is turned off. Please turn it on."
I got the same output with wget. See the bash script at the end of this message.
I don't know how to workaround this. am I missing something? Any idea?
Thanks in advance.
John
Here is the ruby script:
# a ruby script
require 'net/https'
http = Net::HTTP.new('www.google.com', 443)
http.use_ssl = true
path = '/accounts/ServiceLoginAuth'
email='john#gmail.com'
password='topsecret'
# form inputs from the login page
data = "Email=#{email}&Passwd=#{password}&dsh=7379491738180116079&GALX=irvvmW0Z-zI"
headers = { 'Content-Type' => 'application/x-www-form-urlencoded',
'user-agent' => "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/6.0"}
# Post the request and print out the response to retrieve our authentication token
resp, data = http.post(path, data, headers)
puts resp
resp.each {|h, v| puts h+'='+v}
#warning: peer certificate won't be verified in this SSL session
Here is the bash script:
# A bash script for wget
CMD=""
CMD="$CMD --keep-session-cookies --save-cookies cookies.tmp"
CMD="$CMD --no-check-certificate"
CMD="$CMD --post-data='Email=john#gmail.com&Passwd=topsecret&dsh=-8408553335275857936&GALX=irvvmW0Z-zI'"
CMD="$CMD --user-agent='Mozilla'"
CMD="$CMD https://www.google.com/accounts/ServiceLoginAuth"
echo $CMD
wget $CMD
wget --load-cookies="cookies.tmp" http://groups.google.com/group/mygroup/topics?tsc=2
Have you tried with mechanize for ruby?
Mechanize library is used for automating interaction with website; you could log in to google and browse your private google group saving what you need.
Here an example where mechanize is used for gmail scraping.
I did this previously by logging in manually with Firefox and then used Chickenfoot to automate browsing and scraping.
Found this PHP Solution to scraping private Google Groups.
I'm using Merb and DataMapper with a MySQL db. I want to access the database name, user, and password from a Rake task for my Merb app. I guess I could YAML.load() the the database.yml, but that seems ugly. Any ideas?
desc "outputs database connection parameters"
task :db_conn => :merb_env do |t|
puts "Username: #{DataMapper.repository.adapter.uri.user}"
puts "Password: #{DataMapper.repository.adapter.uri.password}"
puts "Database: #{DataMapper.repository.adapter.uri.path.split('/').last}"
end
The interesting part there is the => :merb_env bit. That ensures that the "merb_env" task has executed before your task does. This simply loads up the Merb environment, at which point you can proceed to inspect its configuration.
I have written a ruby script which opens up dlink admin page in firefox and does a ADSL connection or disconnection.
I could run this script in the terminal without any problem. But if I put it as cron job, it doesn't fire up firefox.
This is the entry I have in crontab
# connect to dataone
55 17 * * * ruby /home/raguanu/Dropbox/nettie.rb >> /tmp/cron_test
I see the following entries in /tmp/cron_test. So it looks like the script indeed ran.
PROFILE:
i486-linux
/usr/bin/firefox -jssh
But I couldn't figure out why I didn't see firefox opening up, for this automation to work. Here is /home/raguanu/Dropbox/nettie.rb
#!/usr/bin/ruby -w
require 'rubygems'
require 'firewatir'
require 'optiflag'
module Options extend OptiFlagSet
character_flag :d do
long_form 'disconnect'
description 'Mention this flag if you want to disconnect dataone'
end
flag :l do
optional
long_form 'admin_link'
default 'http://192.168.1.1'
description 'Dlink web administration link. Defaults to http://192.168.1.1'
end
flag :u do
optional
long_form 'user'
default 'admin'
description 'Dlink administrator user name. Defaults to "admin"'
end
flag :p do
optional
long_form 'password'
default 'admin'
description 'Dlink administrator password. Defaults to "admin"'
end
flag :c do
optional
long_form 'connection_name'
default 'bsnl'
description 'Dataone connection name. Defaults to "bsnl"'
end
extended_help_flag :h do
long_form 'help'
end
and_process!
end
class DlinkAdmin
include FireWatir
def initialize(admin_link = "http://192.168.1.1", user = 'admin', pwd = 'admin')
#admin_link, #user, #pwd = admin_link, user, pwd
end
def connect( connection_name = 'bsnl' )
goto_connection_page connection_name
# disconnect prior to connection
#browser.button(:value, 'Disconnect').click
# connect
#browser.button(:value, 'Connect').click
# done!
#browser.close
end
def disconnect( connection_name = 'bsnl' )
goto_connection_page connection_name
# disconnect
#browser.button(:value, 'Disconnect').click
# done!
#browser.close
end
private
def goto_connection_page( connection_name = 'bsnl')
#browser ||= Firefox.new
#browser.goto(#admin_link)
# login
#browser.text_field(:name, 'uiViewUserName').set(#user)
#browser.text_field(:name, 'uiViewPassword').set(#pwd)
#browser.button(:value,'Log In').click
# setup > dataone
#browser.image(:alt, 'Setup').click
#browser.link(:text, connection_name).click
end
end
admin = DlinkAdmin.new(Options.flags.l, Options.flags.u, Options.flags.p)
unless Options.flags.d?
admin.connect( Options.flags.c )
else
admin.disconnect( Options.flags.c )
end
Any help is appreciated.
You need to have a DISPLAY environment pointing at a valid X-server. This could either involve setting it to the value ":0.0" (without quotes), such that it refers to your local standard DISPLAY.
There's a few things to keep in mind though:
You could run an X virtual frame buffer (xvfb), so that Firefox simply uses that as it's display. This would mean that Firefox would be able to do all its graphical operations, but that it would be independent of your standard graphical environment. You'll have to set the DISPLAY variable appropriately so that it points to the xvfb instance. For instance, if you invoke xvfb as follows:
Xvfb :1 -screen 0 1600x1200x32
Then you'll be able to use this by setting the DISPLAY variable to :1
You're starting a full-blown firefox instance to simply connect or disconnect your modem. You would most likely be able to use "curl" to send the appropriate HTTP requests to the server, such that it performs a connect or disconnect for you. One way to trivially see what you should recreate would be to install a Firefox plugin such as LiveHTTPHeaders and note down the most important HTTP requests as you perform the actions manually.
There's even a ruby binding for curl:
libcurl for Ruby. The resulting script should be much smaller than your current script.
Programs run from cron don't have your interactive environment. Therefore they don't have and DISPLAY variable, and so you can't run any X (graphical) programs, e.g. Firefox.
I would suggest doing the HTTP connections yourself, in ruby, rather than trying to automate Firefox.
the crontab entry is wrong
it is like
#min hour day month dow user command
55 17 * * * ur_user_is_missing ruby /home/raguanu/Dropbox/nettie.rb >> /tmp/cron_test