Splinter .type() text then variable - python

I am attempting to use splinter as a bot on a browser game.
This is my main code block
lastMess = ""
mainMess = ""
userName = ""
bailOut = 0
intCommand = "/whoami"
while bailOut == 0:
if browser.find_by_css('.chatMessage-main').first.text != lastMess:
lastMess = browser.find_by_css('.chatMessage-main').first.text
mainMess = browser.find_by_css('.chatMessage-main').first
userName = mainMess.find_by_css('.chatMessage-text').first.text
print(browser.find_by_css('.chatMessage-main').first.text)
print(mainMess.find_by_css('.chatMessage-message').text)
if intCommand == mainMess.find_by_css('.chatMessage-message').text:
browser.find_by_id('chat_input').type("You are ",userName)
print(browser.find_by_id('chat_input').type("You are ",userName))
browser.find_by_id('chat_submit').click()
print("Reply Sent")
It works properly if I just do this
browser.find_by_id('chat_input').type("You are")
or
browser.find_by_id('chat_input').type(userName)
but not if they are together
browser.find_by_id('chat_input').type("You are ",userName)
Is there anyway to do this?

As I was typing this I figured out an answer
if intCommand == mainMess.find_by_css('.chatMessage-message').text:
browser.find_by_id('chat_input').type("You are ")
browser.find_by_id('chat_input').type(userName)
browser.find_by_id('chat_submit').click()
print("Reply Sent")
If I just do two different lines it works. Its probably not the most efficient but it does the job

Related

Find and replace regex within text file (mac addresses)

This has been asked other places, but no joy when trying those solutions. I am trying to search and replace using open(file) instead of file input. Reason is I am printing a "x of y completed" message as it works (fileinput puts that in the file and not to terminal). My test file is 100 mac addresses separated by new lines.
All I would like to do is find the regex matching a mac address and replace it with "MAC ADDRESS WAS HERE". Below is what I have and it is only putting the replace string once at bottom of file.
#!/usr/bin/env python3
import sys
import getopt
import re
import socket
import os
import fileinput
import time
file = sys.argv[1]
regmac = re.compile("^(([a-fA-F0-9]{2}-){5}[a-fA-F0-9]{2}|([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}|([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})?$")
regmac1 = "^(([a-fA-F0-9]{2}-){5}[a-fA-F0-9]{2}|([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}|([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})?$"
regv4 = re.compile(r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')
regv41 = '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
menu = {}
menu['1']="MAC"
menu['2']="IPV4"
menu['3']="IPV6"
menu['4']="STRING"
menu['5']="EXIT"
while True:
options=menu.keys()
sorted(options)
for entry in options:
print(entry, menu[entry])
selection = input("Please Select:")
if selection == '1':
print("MAC chosen...")
id = str('mac')
break
elif selection == '2':
print("IPV4 chosen")
id = str('ipv4')
break
elif selection == '3':
print("IPV6 chosen")
id = str('ipv6')
break
elif selection == '4':
print("String chosen")
id = str('string')
break
elif selection == '5':
print("Exiting...")
exit()
else:
print("Invalid selection!")
macmatch = 0
total = 0
while id == 'mac':
with open(file, 'r') as i:
for line in i.read().split('\n'):
matches = regmac.findall(line)
macmatch += 1
print("I found",macmatch,"MAC addresses")
print("Filtering found MAC addresses")
i.close()
with open(file, 'r+') as i:
text = i.readlines()
text = re.sub(regmac, "MAC ADDRESS WAS HERE", line)
i.write(text)
The above will put "MAC ADDRESS WAS HERE", at the end of the last line while not replacing any MAC addresses.
I am fundamentally missing something. If someone would please point me in right direction that would be great!
caveat, I have this working via fileinput, but cannot display progress from it, so trying using above. Thanks again!
All, I figured it out. Posting working code just in case someone happens upon this post.
#!/usr/bin/env python3
#Rewriting Sanitizer script from bash
#Import Modules, trying to not download any additional packages. Using regex to make this python2 compatible (does not have ipaddress module).
import sys
import getopt
import re
import socket
import os
import fileinput
import time
#Usage Statement sanitize.py /path/to/file, add help statement
#Test against calling entire directories, * usage
#Variables
file = sys.argv[1]
regmac = re.compile("^(([a-fA-F0-9]{2}-){5}[a-fA-F0-9]{2}|([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}|([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})?$")
regmac1 = "^(([a-fA-F0-9]{2}-){5}[a-fA-F0-9]{2}|([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}|([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})?$"
regv4 = re.compile(r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')
regv41 = '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
#Functions
menu = {}
menu['1']="MAC"
menu['2']="IPV4"
menu['3']="IPV6"
menu['4']="STRING"
menu['5']="EXIT"
while True:
options=menu.keys()
sorted(options)
for entry in options:
print(entry, menu[entry])
selection = input("Please Select:")
if selection == '1':
print("MAC chosen...")
id = str('mac')
break
elif selection == '2':
print("IPV4 chosen")
id = str('ipv4')
break
elif selection == '3':
print("IPV6 chosen")
id = str('ipv6')
break
elif selection == '4':
print("String chosen")
id = str('string')
break
elif selection == '5':
print("Exiting...")
exit()
else:
print("Invalid selection!")
macmatch = 0
total = 0
while id == 'mac':
with open(file, 'r') as i:
for line in i.read().split('\n'):
matches = regmac.findall(line)
macmatch += 1
print("I found",macmatch,"MAC addresses")
print("Filtering found MAC addresses")
i.close()
with open(file, 'r') as i:
lines = i.readlines()
with open(file, 'w') as i:
for line in lines:
line = re.sub(regmac, "MAC ADDRESS WAS HERE", line)
i.write(line)
i.close()
break
The above overwrites the regex match (found MAC address) with "MAC ADDRESS WAS HERE". Hopefully this helps someone. Any suggestions to make this more efficient or another way to accomplish are welcomed. Will mark as answer once i am able to, 2days.

How to constantly update time variables in a Python Script?

I have an if statement below that I want to execute at exactly 11:45 am every single day. The problem is, when I run my Python script, result.tm_min and result.tm_hour are static, holding whatever time it was when I started the script in th first place. I need some way for these values to change in real-time with the clock. So when the time changes from 11:44 to 11:45, result.tm_min also changes from 44 to 45, allowing for the below if statement to execute. If I could get any help with this, that would be awesome.
I'm currently using the time and datetime libraries for this.
if result.tm_hour == 11:
if result.tm_min == 45:
post_number = random.randint(1, 5)
noun_number = random.randint(1, noun_expand_count)
verb_number = random.randint(1, verb_expand_count)
noun_file = open("nouns.txt", "r")
get_noun_line = noun_file.readlines()
new_noun = get_noun_line[noun_number].strip()
noun_file.close()
verb_file = open("verbs.txt", "r")
get_verb_line = verb_file.readlines()
new_verb = get_verb_line[verb_number].strip()
verb_file.close()
post_file = open("things_to_do.txt", "r")
get_post_line = post_file.readlines()
new_post = get_post_line[post_number].strip()
post_file.close
message = "#joerogan Hello Joe, today's top two priorities are to:", new_post, new_verb, new_noun
print(message)
#api.update_status(message)
Edit: Okay, I did a pip install for the schedule module, tried to rewrite some code, but I'm not getting any output, at all.
def post():
post_number = random.randint(1, 5)
noun_number = random.randint(1, noun_expand_count)
verb_number = random.randint(1, verb_expand_count)
noun_file = open("nouns.txt", "r")
get_noun_line = noun_file.readlines()
new_noun = get_noun_line[noun_number].strip()
noun_file.close()
verb_file = open("verbs.txt", "r")
get_verb_line = verb_file.readlines()
new_verb = get_verb_line[verb_number].strip()
verb_file.close()
post_file = open("things_to_do.txt", "r")
get_post_line = post_file.readlines()
new_post = get_post_line[post_number].strip()
post_file.close
message = "#joerogan Hello Joe, today's top two priorities are to:", new_post, new_verb, new_noun
print(message)
#api.update_status(message)
return
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
global noun_expand_count, verb_expand_count
status = status._json['text']
schedule.every().minute.do(post)
Recalculate the current time immediately before checking:
current = datetime.now()
if current.hour == 11 and current.minute == 45:
# annoy Joe Rogan
However, as others have commented, it might be better to use a purpose-built task scheduling system such as cron.

Is there an equivalent to RStudio's ".rs.askForPassword" in Python?

I want to connect to my database in Python, but i don't want to show my password to other users, like .rs.askForPassword does exactly what i need in RStudio. Here's an example:
library(RODBC)
conn = odbcConnect(dsn = "my_dsn",
uid = "name.last_name",
pwd = .rs.askForPassword("my.password"))
Is there any way to do this in Python?
You may use getpass()
import getpass
p = getpass.getpass(prompt='What is your favorite person? ')
if p.lower() == 'gf':
print 'Right. Off you go.'
else:
print 'Wrong!'

python-ldap unable to do any basic search queries on open server

I have been trying to do some basic search queries, but I am unable to connect to an open LDAP server regardless. I tried a couple of servers, and none of them worked. I used Apache Directory Studio to make sure that the keyword was there but it did not work either way. I tried a variety of different code from different sources.
This was the first one I used
:
https://www.linuxjournal.com/article/6988
import ldap
keyword = "boyle"
def main():
server = "ldap.forumsys.com"
username = "cn=read-only-admin,dc=example,dc=com"
password = "password"
try:
l = ldap.open(server)
l.simple_bind_s(username,password)
print "Bound to server . . . "
l.protocol_version = ldap.VERSION3
print "Searching . . ."
mysearch (l,keyword)
except ldap.LDAPError:
print "Couldnt connect"
def mysearch(l, keyword):
base = ""
scope = ldap.SCOPE_SUBTREE
filter = "cn=" + "*" + keyword + "*"
retrieve_attributes = None
count = 0
result_set = []
timeout = 0
try:
result_id = l.search(base, scope, filter, retrieve_attributes)
while l != 1:
result_id = l.search(base, scope,filter, retrieve_attributes)
result_type, result_data = l.result(result_id, timeout)
if result_data == []:
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
if len (result_set = 0):
print "No Results"
for i in range (len(result_set)):
for entry in result_set[i]:
try:
name = entry[1]['cn'][0]
mail = entry[1]['mail'][0]
#phone = entry[1]['telephonenumber'][0]
#desc = entry[1]['description'][0]
count = count + 1
print name + mail
except:
pass
except ldap.LDAPError, error_message:
print error_message
main()
Every time I ran this program, I received an error
{'desc': u"No such object"}
I also tried this
import ldap
try:
l = ldap.open("ldap.example.com")
except ldap.LDAPError, e:
print e
base_dn = "cn=read-only-admin,dc=example,dc=com"
search_scope = ldap.SCOPE_SUBTREE
retrieve_attributes = None
search_filter = "uid=myuid"
try:
l_search = l.search(base_dn, search_scope, search_filter, retrieve_attributes)
result_status, result_data = l.result(l_search, 0)
print result_data
except ldap.LDAPError, e:
print e
The error on this one was
{'desc': u"Can't contact LDAP server"}
I spent about 5 hours trying to figure this out. I would really appreciate it if you guys could give me some advice. Thanks.
There are several bogus things in there.
I will only comment your first code sample because it can be used by anyone with that public LDAP server.
l = ldap.open(server)
Function ldap.open() is deprecated since many years. You should use function ldap.initialize() with LDAP URI as argument instead like this:
l = ldap.initialize("ldap://ldap.forumsys.com")
l_search = l.search(..)
This is the asynchronous method which just returns a message ID (int) of the underlying OpenLDAP C API (libldap). It's needed if you want to retrieve extended controls returned by the LDAP server along with search results. Is that what you want?
As a beginner you probably want to use the simpler method LDAPObject.search_s() which immediately returns a list of (DN, entry) 2-tuples.
See also: python-ldap -- Sending LDAP requests
while l != 1
This does not make sense at all because l is your LDAPObject instance (LDAP connection object). Note that LDAPObject.search() would raise an exception if it gets an Integer error code from OpenLDAP's libldap. No need to do C-style error checks at this level.
filter = "cn=" + "" + keyword + ""
If keyword can be arbitrary input this is a prone to LDAP injection attacks. Don't do that.
For adding arbitrary input into a LDAP filter use function ldap.filter.escape_filter_chars() to properly escape special characters. Also avoid using variable name filter because it's the name of a built-in Python function and properly enclose the filter in parentheses.
Better example:
ldap_filter = "(cn=*%s*)" % (ldap.filter.escape_filter_chars(keyword))
base = ""
The correct search base you have to use is:
base = "dc=example,dc=com"
Otherwise ldap.NO_SUCH_OBJECT is raised.
So here's a complete example:
import pprint
import ldap
from ldap.filter import escape_filter_chars
BINDDN = "cn=read-only-admin,dc=example,dc=com"
BINDPW = "password"
KEYWORD = "boyle"
ldap_conn = ldap.initialize("ldap://ldap.forumsys.com")
ldap_conn.simple_bind_s(BINDDN, BINDPW)
ldap_filter = "(cn=*%s*)" % (ldap.filter.escape_filter_chars(KEYWORD))
ldap_results = ldap_conn.search_s(
"dc=example,dc=com",
ldap.SCOPE_SUBTREE,
ldap_filter,
)
pprint.pprint(ldap_results)

How to log into SAP silently using win32com methods?

I have a question about SAP silent logon which I implemented using win32com this way
from win32com.client import Dispatch
R3 = Dispatch("SAP.Functions")
R3.Conn.System = 'xxx'
R3.Conn.Client = '100'
# other values needed to pass to R3.Conn
R3.Conn.logon #here is the problem
In VB i can use R3.Conn.Logon(1, True) to make logon siliencely. But in Python Logon seems not to be a method and do not allow me to pass parameters to it.
I tried using R3.Conn.Logon(1, True) in Python, but it returned an error
Logon was not callable.
How should I call silent logon in Python?
Thanks
This works for me.
Still experimenting, I want to add field selection and of course a filter to the RFC_READ_TABLE. But the connection works.
from win32com.client import Dispatch
Functions = Dispatch("SAP.Functions")
Functions.Connection.Client = "000"
Functions.Connection.ApplicationServer = "your server"
Functions.Connection.Language = "EN"
Functions.Connection.User = "you"
Functions.Connection.Password = "your pass"
Functions.Connection.SystemNumber = "00"
Functions.Connection.UseSAPLogonIni = False
if (Functions.Connection.Logon (0,True) == True):
print("Logon OK")
RfcCallTransaction = Functions.Add("RFC_READ_TABLE")
strExport1 = RfcCallTransaction.exports("QUERY_TABLE")
strExport2 = RfcCallTransaction.exports("DELIMITER")
strExport3 = RfcCallTransaction.exports("ROWSKIPS")
strExport4 = RfcCallTransaction.exports("ROWCOUNT")
tblOptions = RfcCallTransaction.Tables("OPTIONS")
#RETURNED DATA
tblData = RfcCallTransaction.Tables("DATA")
tblFields = RfcCallTransaction.Tables("FIELDS")
strExport1.Value = 'AGR_DEFINE'
strExport2.Value = ";"
strExport3.Value = 0
strExport4.Value = 10
if RfcCallTransaction.Call == True:
print ("Function call successful")
#print (tblData.RowCount)
j = 1
while j < tblData.RowCount:
print (tblData(j,"WA"))
j = j + 1

Categories

Resources