Python session close after getting the results - python-3.x

I have a python code which uses session id and gets the output from an url.
I have to logout of the session once i get the results.Is there a way to close the session. I tried all the options such as
s = requests.session()
s.config['keep_alive'] = False
r = requests.post(url=url, data=body, headers={'Connection':'close'})
When i tried to print the session id after the closing the connection it prints the same session id that is used to make the connection.

Related

Attempting to open browser with Specific Profile in Incognito Mode

Attempting to open browser with Specific Profile in Incognito Mode.
After the browser is opened, need to verify that the URL opened the proper page
I am using the following code
browserName = set()
profile_name = 'Person 1
rpa_string = 'https://www.google.ca'
path_br_ch = '/Google/Chrome/Application/chrome.exe'
browserName.add("chrome")
browser_profile = f"--profile-directory={profile_name}"
browser_path = path_br_ch
browser_privacy = "--incognito"
rpa_command = [browser_path, browser_privacy, browser_profile, rpa_string]
browser_process = subprocess.Popen(rpa_command)
# Next step need to verify that the google page is opened
# Please help

Selenium anticaptcha submission

I am trying to fill recaptcha using anticaptcha api.
But I am unable to figure out how to submit response.
Here is what I am trying to do:
driver.switch_to.frame(driver.find_element_by_xpath('//iframe'))
url_key = driver.find_element_by_xpath('//*[#id="captcha-submit"]/div/div/iframe').get_attribute('src')
#site_key = re.search('k=([^&]+)',url_key).group(1)
site_key = '6Ldd2doaAAAAAFhvJxqgQ0OKnYEld82b9FKDBnRE'
api_key = 'api_keys'
url = driver.current_url
client = AnticaptchaClient(api_key)
task = NoCaptchaTaskProxylessTask(url, site_key)
job = client.createTask(task)
job.join()
driver.execute_script("document.getElementById('g-recaptcha-response').innerHTML='{}';".format(job.get_solution_response()))
driver.refresh()
Above code snippet only refreshes the same page and not redirecting to input url.
Then I see that there is a variable in script on the same page and I tried to execute that variable too to submit form just like that
driver.execute_script("var captchaSubmitEl = document.getElementById('captcha-submit');")
driver.refresh()
Which also fails.The webpage is here.

ldap3 add user to group after conn.search

currently, I am writing an AWS Lambda function and the idea is, that someone can send an email to a specific address with a username and AD group and it will trigger the function and add this person to the desired group.
I am using the python module ldap3 and the conn.search part is working, aswell as the addUsersInGroup, but only if I run it separately. If I create a script where I already have the cn or dn name of both user and group and use the addUsersInGroup Function it works, but if I do a conn.search somewhere before it somehow can't establish the connection for the add-to-group part.
from ldap3 import Server, Connection, ALL, NTLM, SUBTREE
from ldap3.extend.microsoft.addMembersToGroups import ad_add_members_to_groups as addUsersInGroups
import email
import os
import json
email = "sample#test.com"
subject = "username,ad-group"
user = subject.split(",")[0]
group = subject.split(",")[1]
emaildomain = email.split("#")[1]
domaingroup = ["test.com"]
adgroups = ["group1","group2"]
server = Server('serverIP', use_ssl=True, get_info=ALL)
conn = Connection(server, OU,
password, auto_bind=True)
def find_user():
user_criteria = "(&(objectClass=user)(sAMAccountName=%s))"%user
if conn.search("OU", user_criteria):
result = str(conn.entries)
user_dn = result.split("-")[0].replace("[DN: ","")
return user_dn
return nouser
def find_group():
group_criteria = "(&(objectClass=group)(sAMAccountName=%s))"%group
if conn.search("OU", group_criteria):
result_group = str(conn.entries)
group_dn = result_group.split("-")[0].replace("[DN: ","")
return group_dn
return nogroup
def add_to_group(user,group):
addUsersInGroups(conn,user,group)
if emaildomain in domaingroup:
user = find_user()
group = find_group()
add_to_group(user,group)
Please note that I had to delete some things off the script for security reasons.
The connection to search for a user or group is working and if I run the add-to-group function it works too, but only running it without any search beforehand.
Somehow I have the feeling that making the conn.search blocks the connection for anything search related and if try to use the same connection for something different e.g. adding a user to group, that request gets blocked.
Here is the error I receive:
Error_Message
Found the solution on this website:
https://github.com/cannatag/ldap3/issues/442
You are getting this error probably due to auto_referrals=True in Connection by default. Try to use:
conn = Connection(server, "cn=xxx,cn=users,dc=wwww,dc=zzzz,dc=com", "my_pass", auto_bind=True, auto_referrals=False) and do not search and another DC.

Flask sessions: PERMANENT_SESSION_LIFETIME not being set correctly

So I am using a flask session. I am using the filesystem type so that I can store more session data than I otherwise could. My users want to keep session timeouts long, and the site uses minimal server storage, so this is fine. However, when I try to set the timeout session to 24 hours below, it still times out after 30 minutes.
application = Flask(__name__)
SECRET_KEY = os.urandom(32)
application.config['SESSION_PERMANENT'] = True
application.config['SESSION_TYPE'] = 'filesystem'
application.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours = 24)
application.config['SECRET_KEY'] = SECRET_KEY
Session(application)
#application.before_request
def make_session_permanent():
session.permanent = True
application.permanent_session_lifetime = timedelta(hours = 24)
What am I doing wrong here?
I believe I have found the issue, which was in the line : SECRET_KEY = os.urandom(32). Every time the app restarted (idle window in browser reloaded), session data was erased as a new secret key was generated, meaning the browser could not find the cookies it needed. I generated one key, externally, and then hardcoded this value into my code so it is the same every time.
I would change the line with session.permanent =true to session.modified = True and see if it works then.

Cherrypy 3.2 sessions broken, or am I doing it wrong?

Running python 3 with cherrypy 3.2, and have been having a host of problems. First of all, to get cookies to work, i had to fake a fqdn in /etc/hosts.
e.g.
http://test:8080 [no cookies]
http://test.local:8080 [cookies work]
After this, I tried to get sessions to work, but I am getting a new session id each time, and no session_id value is being set in a cookie anywhere in the browser.
class HelloWorld:
#cherrypy.expose
def index(self, *args):
print("\n\n")
### test cookies (works fine, no problems)
print(cherrypy.request.cookie)
cherrypy.response.cookie['c1'] = 'val1'
cherrypy.response.cookie['c1']['max-age'] = '3600'
cherrypy.response.cookie['d1'] = 'val2'
cherrypy.response.cookie['d1']['max-age'] = '3600'
### test sessions (doesn't work)
print(cherrypy.session.load()) # always returns None
print(cherrypy.session.id) # different every refresh
print(cherrypy.session.get('foo')) # always returns None
cherrypy.session['foo'] = 'bar'
cherrypy.session.save() # apparently has no effect
return "Hello world!"
Can anyone offer some advice or suggestions? I see that no no cookie with the session id is being set in chrome, even though my other values are.
My config looks like:
'/': {'tools.sessions.on': True,
'tools.sessions.timeout': 7200}}
Any ideas?
I was facing the same problem. I added tools.sessions.name to the cherrypy config and now it works

Resources