A script to automatically login to an account once a month - autologin

DynDNS requires a login to an account once a month to keep the free domains active. Is it possible to write simple script (in Linux) to do this? The login page is this.

If you want to write it in python and host the script on a server such that it runs indefinetaly, you can use the Mechanize library to log in for you and the time built in to do it once a month.
Mechanize: http://stockrt.github.io/p/emulating-a-browser-in-python-with-mechanize/
Time: http://docs.python.org/2/library/time.html
Free hosting: https://www.heroku.com/

You mean like this:
import re
import mechanize
username = "username"
password = "password"
success_verification_text = "Log Out"
br = mechanize.Browser()
response = br.open("https://account.dyn.com/")
#select the login form
for form1 in br.forms():
form = form1
break;
br.select_form(nr=0)
form["username"] = username
form["password"] = password
response = br.submit()
if success_verification_text in response.read():
print "SUCCESS"
else:
print "FAILED"
https://gist.github.com/mandarl/6007396

If you want to login successfully you will need to select login form.
Form ID changes between requests (loginNNN) so it's best to search for it by name.
Working example (requires mechanize):
import re
import mechanize
username = "xxx"
password = "xxxxxx"
success_verification_text = "Log Out"
br = mechanize.Browser()
response = br.open("https://account.dyn.com/")
# select the login form
cnt = 0
for frm in br.forms():
if str(frm.attrs["id"]).find("login") != -1:
form = frm
break
cnt += 1
br.select_form(nr=cnt)
form["username"] = username
form["password"] = password
response = br.submit()
if success_verification_text in response.read():
print ("SUCCESS")
else:
print ("FAILED")

Related

Execute customized script when launching instance using openstacksdk

I'm new to Openstack and I'm trying to create a tool so that I can launch any number of instances in an Openstack cloud. This was easily done using the nova-client module of openstacksdk.
Now the problem is that I want to make the instances execute a bash script as they are created by adding it as a userdata file, but it doesn't execute. This is confusing because I don't any error or warning message. Does anyone know what could it be?
Important parts of the code
The most important parts of the Python program are the function which gets the cloud info, the one that creates the instances and the main function, . I'll post them here as #Corey told.
"""
Function that allow us to log at cloud with all the credentials needed.
Username and password are not read from env.
"""
def get_nova_credentials_v2():
d = {}
user = ""
password = ""
print("Logging in...")
user = input("Username: ")
password = getpass.getpass(prompt="Password: ", stream=None)
while (user == "" or password == ""):
print("User or password field is empty")
user = input("Username: ")
password = getpass.getpass(prompt="Password: ", stream=None)
d['version'] = '2.65'
d['username'] = user
d['password'] = password
d['project_id'] = os.environ['OS_PROJECT_ID']
d['auth_url'] = os.environ['OS_AUTH_URL']
d['user_domain_name'] = os.environ['OS_USER_DOMAIN_NAME']
return d
Then we have the create_server function:
"""
This function creates a server using the info we got from JSON file
"""
def create_server(server):
s = {}
print("Creating "+server['compulsory']['name']+"...")
s['name'] = server['compulsory']['name']
s['image'] = server['compulsory']['os']
s['flavor'] = server['compulsory']['flavor']
s['min_count'] = server['compulsory']['copyNumber']
s['max_count'] = server['compulsory']['copyNumber']
s['userdata'] = server['file']
s['key_name'] = server['compulsory']['keyName']
s['availability_zone'] = server['compulsory']['availabilityZone']
s['nics'] = server['compulsory']['network']
print(s['userdata'])
if(exists("instalacion_k8s_docker.sh")):
print("Exists")
s['userdata'] = server['file']
nova.servers.create(**s)
And now the main function:
"""
Main process: First we create a connection to Openstack using our credentials.
Once connected we cal get_serverdata function to get all instance objects we want to be created.
We check that it is not empty and that we are not trying to create more instances than we are allowed.
Lastly we create the instances and the program finishes.
"""
credentials = get_nova_credentials_v2()
nova = client.Client(**credentials)
instances = get_serverdata()
current_instances = len(nova.servers.list())
if not instances:
print("No instance was writen. Check instances.json file.")
exit(3)
num = 0
for i in instances:
create_server(i)
exit(0)
For the rest of the code you can access to this public repo on github.
Thanks a lot!
Problem solved
The problem was the content of the server['file'] as #Corey said. It cannot be the Path to the file where you wrote the data but the content of it or a file type object. In the case of OpenstackSDK it must be base64 encoded but it is not the case in Novaclient.
Thanks a lot to #Corey for all the help! :)

LDAP Query in Python3

I have an LDAP Query which is running perfectly fine in my terminal
ldapsearch -h ldap.mygreatcompany.com -D user#mygreatcompany.COM -w "$ldappassword" -b "DC=abc,DC=mygreatcompany,DC=com" -s sub "(mail=user1#mygreatcompany.COM)" sAMAccountName
I want to run this command in python3, I followed other answers from StackOverflow and wrote something like this,
import ldap
l = ldap.initialize('ldap://ldap.mygreatcompany.com')
binddn = "user#mygreatcompany.COM"
pw = #ldappassword
basedn = "DC=abc,DC=mygreatcompany,DC=com"
searchAttribute = ["sAMAccountName"]
searchFilter = "(&(mail=user1#mygreatcompany.COM')(objectClass=*))"
searchScope = ldap.SCOPE_SUBTREE
l.simple_bind_s(binddn, pw)
ldap_result_id = l.search_s(basedn, searchScope, searchFilter, searchAttribute)
#Get result
l.unbind_s()
But Here I am not getting the result from ldap_result_id. Can anybody help what is the correct way to do this query?
Thanks
It turns out that I was not using connection.set_option(ldap.OPT_REFERRALS, 0) in the code and there is some issue in LDAP which automatically chases the referrals internally with anonymous access which fails.
Here is the working code:
def get_user_id(email):
# Seach fiter for user mail
searchFilter = "mail={}".format(email)
try:
# binding to ldap server
connection = ldap.initialize('ldap://yourcompanyhost')
connection.set_option(ldap.OPT_REFERRALS, 0)
connection.protocol_version = ldap.VERSION3
connection.simple_bind_s(binddn, pwd)
# get result
ldap_result_id = connection.search_s(basedn, searchScope, searchFilter, searchAttribute)
# extract the id
saMAccount = ldap_result_id[0][1]["sAMAccountName"][0].decode('utf-8')
except ldap.INVALID_CREDENTIALS:
print("Your username or password is incorrect.")
except ldap.LDAPError as e:
print(e)
except:
print("Data doesn't exist for this user")
connection.unbind_s()
print(get_user_id("user1#mygreatcompany.COM"))

Selenium to submit recaptcha using 2captcha Python

I am trying to submit Recaptcha on a search form using Python3, Selenium, and 2captcha.
Everything is working fine except submitting the Recaptcha after sending google-tokin in the text-area of Recaptcha.
Please guide me what am I missing?
When I look into my Selenium Webdriver window it shows Recaptcha text-area filled with google-tokin but I am not able to submit it to continue for search result.
Thankyou.
from selenium import webdriver
from time import sleep
from datetime import datetime
from twocaptcha import TwoCaptcha
import requests
## Launching webdriver
driverop = webdriver.ChromeOptions()
driverop.add_argument("--start-maximized")
driver = webdriver.Chrome("chromedriver/chromedriver",options=driverop)
url = "https://app.skipgenie.com/Account/Login"
sleep(randint(5,10))
email = "..."
password = ".."
input_data = pd.read_excel("input_data.xlsx")
user_Data = []
driver.get(url)
driver.find_element_by_id("Email").send_keys(email)
driver.find_element_by_id("Password").send_keys(password)
driver.find_element_by_class_name("btn-lg").click()
driver.find_element_by_id("firstName").send_keys(input_data.iloc[0][0])
driver.find_element_by_id("lastName").send_keys(input_data.iloc[0][1])
driver.find_element_by_id("street").send_keys(input_data.iloc[0][2])
driver.find_element_by_id("city").send_keys(input_data.iloc[0][3])
driver.find_element_by_id("state").send_keys(input_data.iloc[0][4])
driver.find_element_by_id("zip").send_keys(int(input_data.iloc[0][5]))
# 2Captcha service
service_key = 'ec.....' # 2captcha service key
google_site_key = '6LcxZtQZAAAAAA7gY9-aUIEkFTnRdPRob0Dl1k8a'
pageurl = 'https://app.skipgenie.com/Search/Search'
url = "http://2captcha.com/in.php?key=" + service_key + "&method=userrecaptcha&googlekey=" + google_site_key + "&pageurl=" + pageurl
resp = requests.get(url)
if resp.text[0:2] != 'OK':
quit('Service error. Error code:' + resp.text)
captcha_id = resp.text[3:]
fetch_url = "http://2captcha.com/res.php?key="+ service_key + "&action=get&id=" + captcha_id
for i in range(1, 10):
sleep(5) # wait 5 sec.
resp = requests.get(fetch_url)
if resp.text[0:2] == 'OK':
break
driver.execute_script('var element=document.getElementById("g-recaptcha-response"); element.style.display="";')
driver.execute_script("""
document.getElementById("g-recaptcha-response").innerHTML = arguments[0]
""", resp.text[3:])
Answering the question so the people who encounter situations like this could get help from this answer.
I was missing that after you get google token you need to display recaptcha text-area and send google-token to text-area like this
To display text-area of recaptcha.
driver.execute_script('var element=document.getElementById("g-recaptcha-response"); element.style.display="";')
after that send google token like this:
driver.execute_script("""
document.getElementById("g-recaptcha-response").innerHTML = arguments[0]
""", resp.text[3:])
then you need to make text-area display to none so the search button near repcatcha is clickable.
driver.execute_script('var element=document.getElementById("g-recaptcha-response"); element.style.display="none";')
then you need to click on the search button to get the search result.

Undefined method `update_attributes' for nil:NilClass When Implementing Stripe Connect

I attempting to implement Stripe Connect in my Rails 6 app.
I can successfully redirect the User to Stripe on-boarding.
I'm using the omniauth-stripe-connect gem
I'm getting undefined method update_attributes' for nil:NilClassfor theif #user.update_attributes({` line
The error that I'm getting is after the User has completed Stripe On-boarding I redirect them to my application. Below is my OmniauthCallbacksController:
class PetProviders::OmniauthCallbacksController < Devise::OmniauthCallbacksController
# You should also create an action method in this controller like this:
# def twitter
# end
def stripe_connect
auth_data = request.env["omniauth.auth"]
#user = current_pet_provider
if #user.update_attributes({
provider_name: auth_data.provider,
uid: auth_data.uid,
access_code: auth_data.credentials.token,
publishable_key: auth_data.info.stripe_publishable_key,
})
sign_in_and_redirect #user, event: :authentication
flash[:notice] = "Stripe Account Created and Connected" if is_navigational_format?
else
session["devise.stripe_connect_data"] = request.env["omniauth.auth"]
redirect_to root_path
end
end
# More info at:
# https://github.com/plataformatec/devise#omniauth
# GET|POST /resource/auth/twitter
# def passthru
# super
# end
# GET|POST /users/auth/twitter/callback
# def failure
# super
# end
# protected
# The path used when OmniAuth fails
# def after_omniauth_failure_path_for(scope)
# super(scope)
# end
end
I suspect that current_pet_provider is empty!
How do I get current_pet_provider within OmniauthCallbacksController ?
It looks like you need to retrieve the #user from Omniauth before you can use it? https://github.com/omniauth/omniauth#integrating-omniauth-into-your-application
Using the code snippet below, I first obtain the user using the email and then I insert the new data that I want.
data = auth_data.info
#user = PetProvider.find_by(email: data["email"])
With everything put together, my stripe_connect method now looks like so;
def stripe_connect
auth_data = request.env["omniauth.auth"]
data = auth_data.info
#user = PetProvider.find_by(email: data["email"])
if #user
#user.provider_name = auth_data.provider
#user.uid = auth_data.uid
#user.access_code = auth_data.credentials.token
#user.publishable_key = auth_data.info.stripe_publishable_key
#user.save!
redirect_to root_path
flash[:notice] = "Stripe Account Created and Connected" if is_navigational_format?
else
session["devise.stripe_connect_data"] = request.env["omniauth.auth"]
flash[:error] = "Unable to Connect To Stripe"
redirect_to root_path
end
end

parsing data from imaplib emails

So I found a this script in another thread. Everything works fine except I cannot get the message "From:", "Date:", and the "Subject:" to show. They show up as NONE.
Below is the code
import imaplib
from email.parser import HeaderParser
myHost = 'imap.gmail.com'
myUsername = 'username'
myPassword = 'password'
m = imaplib.IMAP4_SSL(myHost)
m.login(myUsername,myPassword)
# get list of mailboxes
list = m.list()
# select which mail box to process
m.select("Inbox")
resp, data = m.uid('search',None, "ALL") # search and return Uids
uids = data[0].split()
mailparser = HeaderParser()
for uid in uids:
resp,data = m.uid('fetch',uid,"(BODY[HEADER])")
msg = mailparser.parsestr(str(data[0][1]))
print (msg['From:'],msg['Date:'],msg['Subject:']) # Doesnt Work
print(m.expunge())
m.close() # close the mailbox
m.logout() # logout

Resources