Multiple else condition in python - python

I have python script with will read each IP from file and install agent on that IP using password, there are 5-6 passwords and if one password doesn't work it should try with other all passwords one by one.
This is my script:
##Reading values from SucessfullIp.txt
with open('/root/nix_bsd_mac_inventory-master/SucessfullIp.txt') as f:
ips = set(line.rstrip() for line in f)
##Reading Unique Ip's values
with open("/root/nix_bsd_mac_inventory-master/Unique.txt") as fp:
for line in fp:
line = line.rstrip()
## Comparing unique ip's if ip is already has scanned
if line in ips:
print('{}: Ip is Already Tried: '.format(line))
else:
##Creating inventory.cfg file on the fly for each ip
f3 = open("/root/nix_bsd_mac_inventory-master/inventory.cfg", "w")
print "Processing Ip: " + line
f3.write("[device42_access]" + "\n" +
"base_url = https://1.8.0.3" + "\n" +
"username = uname" + "\n" +
"secret = abcd" + "\n" +
"[discover]" + "\n" +
"cpu= true" + "\n" +
"hardware = true" + "\n" +
"memory = true" + "\n" +
"[access]"+ "\n" +
"credentials = username:passowrd1" + "\n" + ##here we are giving credentials and we have 5-6 passwords
f3.close()
p = subprocess.Popen(["./d42_linux_autodisc_v620"], stdout=subprocess.PIPE) ##This script will require inventory.cfg file created above
p1 = str(p.communicate())
if '1 devices were successfully added/updated' in p1:
print ('Sucessfull Completed Ip: ' +line)
f6 = open("/root/nix_bsd_mac_inventory-master/SucessfullIp.txt","a")
f6.write("\n"+line)
f6.close()
else:
print "Unsuccessfull"
##here want it to check it with other passwords as well

You should iterate over a list of your passwords and break out of the loop if one is successful.
You had a syntax error in the following snippet:
"credentials = username:passowrd1" + "\n" +
This should not end with a + as you are not concatenating anything else to the string.
It will be useful for you to look up break, continue, and else statements that you can use with loops as I have used them in the answer.
I have removed all of your comments, and added comments of my own to explain the logic.
with open("/root/nix_bsd_mac_inventory-master/Unique.txt") as fp:
for line in fp:
line = line.rstrip()
if line in ips:
print('{}: Ip is Already Tried: '.format(line))
continue # Continue means it will skip to the next password
passwords = ['password1', 'password2', 'password3']
for password in passwords:
f3 = open("/root/nix_bsd_mac_inventory-master/inventory.cfg",
"w")
print "Processing Ip: " + line
f3.write("[device42_access]" + "\n" +
"base_url = https://1.8.0.3" + "\n" +
"username = uname" + "\n" +
"secret = abcd" + "\n" +
"[discover]" + "\n" +
"cpu= true" + "\n" +
"hardware = true" + "\n" +
"memory = true" + "\n" +
"[access]" + "\n" +
"credentials = username:" + password + "\n" # Fixed typo here
f3.close()
p = subprocess.Popen(["./d42_linux_autodisc_v620"],
stdout=subprocess.PIPE)
p1 = str(p.communicate())
if '1 devices were successfully added/updated' in p1:
print('Sucessfull Completed Ip: ' + line)
f6 = open("/root/nix_bsd_mac_inventory-master/SucessfullIp.txt", "a")
f6.write("\n" + line)
f6.close()
break # If successful it breaks, so don't need an else
print "Password %s Unsuccessfull" % password
else:
# This happens when there are no more passwords to attempt
print "No passwords were successful"

You can do it using a for loop and a single else:
for password in list_of_password:
...
"credentials = username:" + password + "\n"
...
if '1 devices were successfully added/updated' in p1:
...
break
else:
print "Unsuccessfull"

Related

IF statement behaving the opposite way

I've written a little script that scans a text file in the below format.
Then outputs a different text file with the redirected URLs, only if there is a redirection. Otherwise, I wanted to print out "No redirection". But for some reason, the exact opposite happens.
Below is my code, could you please explain me what I did wrong?
import urllib.request
inc_input = input("Please enter the file name\n")
file_name = open(inc_input)
f = open('output.txt', 'w')
for line in file_name:
eachurl = line.strip()
redirected = urllib.request.urlopen(eachurl)
finalurl = redirected.geturl()
if eachurl == finalurl:
f.write(eachurl + "\t" + finalurl + "\n")
else:
f.write(eachurl + "\t" + "No redirection" + "\n")
f.close()
Your logic seems opposite to what you expect, I've added comments to clarify:
if eachurl == finalurl:
# no redirection happened since we're in the original url (==)
f.write(eachurl + "\t" + finalurl + "\n")
else:
# redirection happened, different url
f.write(eachurl + "\t" + "No redirection" + "\n")
Use not to reverse the condition or reverse the bodies. Currently the message is misleading.
if eachurl != finalurl: #when the urls are not same, it's a redirection
f.write(eachurl + "\t" + finalurl + "\n")
else:
f.write(eachurl + "\t" + "No redirection" + "\n")

How to encrypt a .bin file

I need to encrypt 3 .bin files which contain 2 keys for Diffie-Hellman. I have no clue how to do that, all I could think of was what I did in the following Python file. I have an example what the output should look like but my code doesn't seem to produce the right keys. The output file server.ini is used by a client to connect to a server.
import base64
fileList = [['game_key.bin', 'Game'], ['gate_key.bin', 'Gate'], ['auth_key.bin', 'Auth']]
iniList = []
for i in fileList:
file = open(i[0], 'rb')
n = list(file.read(64))
x = list(file.read(64))
file.close()
n.reverse()
x.reverse()
iniList.append(['Server.' + i[1] + '.N "' + base64.b64encode("".join(n)) + '"\n', 'Server.' + i[1] + '.X "' + base64.b64encode("".join(x)) + '"\n'])
iniList[0].append('\n')
#time for user Input
ip = '"' + raw_input('Hostname: ') + '"'
dispName = 'Server.DispName ' + '"' + raw_input('DispName: ') + '"' + '\n'
statusUrl = 'Server.Status ' + '"' + raw_input('Status URL: ') + '"' + '\n'
signupUrl = 'Server.Signup ' + '"' + raw_input('Signup URL: ') + '"' + '\n'
for l in range(1, 3):
iniList[l].append('Server.' + fileList[l][1] + '.Host ' + ip + '\n\n')
for l in [[dispName], [statusUrl], [signupUrl]]:
iniList.append(l)
outFile = open('server.ini', 'w')
for l in iniList:
for i in l:
outFile.write(i)
outFile.close()
The following was in my example file:
# Keys are Base64-encoded 512 bit RC4 keys, as generated by DirtSand's keygen
# command. Note that they MUST be quoted in the commands below, or the client
# won't parse them correctly!
I also tried it without inverting n and x

python wont write even when I use f.close

I'm trying to write some code that outputs some text to a list. output is a variable that is a string which is the name of the file to be written. However whenever I look at the file nothing is written.
with open(output, 'w') as f:
f.write("Negative numbers mean the empty space was moved to the left and positive numbers means it was moved to the right" + '\n')
if A == True:
the_h = node.h
elif A== False:
the_h = 0
f.write("Start " + str(node.cargo) + " " + str(node.f) +" " +str(the_h)+" " + '\n')
if flag == 0:
flag = len(final_solution)
for i in range (1,flag):
node = final_solution[i]
f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + " " + str(node.f) +'\n')
f.close()
Program looks ok, check if the output is set ok, I set as a dummy filename, it worked, presuming code within the block after open has no compiler/interpreter error. The output file should be in the same directory where the source is.
output = "aa.txt"
with open(output, 'w') as f:
f.write("Negative numbers mean the empty space was moved to the left and positive numbers means it was moved to the right" + '\n')
if A == True:
the_h = node.h
elif A== False:
the_h = 0
f.write("Start " + str(node.cargo) + " " + str(node.f) +" " +str(the_h)+" " + '\n')
if flag == 0:
flag = len(final_solution)
for i in range (1,flag):
node = final_solution[i]
f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + " " + str(node.f) +'\n')
f.close()
You should not add f.close(), as the with statement will do it for you. Also ensure you don't reopen the file elsewhere with open(output, 'w') as that will erase the file.

overwrite words in text file with python

I created a text file that contains in the first line a counter of created users and the rest of the lines the text contains user name, password..
for example:
2
username Name Last_name Password
username1 Name Last_name1 Password1
I'm using the following commands:
def SaveDatA(self):
#if self.CheckValid() == False:
#return
with open("data.txt","a") as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
I want to update the counter to the first line
Do you want this?
f1_lines = open('data.txt', 'r').readlines()
with open('data.txt','w') as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
f1_lines[0]=str(self.counter)+'\n'
f.write(''.join(f1_lines))
With readlines() you create a list contain all of lines in the file so you change the first index of that list with f1_lines[0]=str(self.counter)+'\n' then rewrite it in to the file !
After a lot of trials this code work's:
with open("data.txt","a") as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
fileCopy = open('data.txt', 'r').readlines()
fileCopy[0] = fileCopy[0][1:]
with open("data.txt","w") as f:
f.write(str(self.counter)+" ")
f.write("".join(fileCopy))
but maybe there is another better way ?

I'm trying to understand how to call a function from another function in the same class

I'm attempting to login to an Ubuntu server and search logs at several different paths with a function that already works locally (Python 2.7 - win7 machine). Below is the function of how I login and select the logs (also, the basis of my program is Python's cmd module):
def do_siteserver(self, line):
import paramiko
paramiko.util.log_to_file('c:\Python27\paramiko-wininst.log')
host = '10.5.48.65'
portNum = raw_input("\nEnter a port number: ")
while True:
try:
port = int(portNum)
break
except:
print "\nPort is not valid!!!"
break
transport = paramiko.Transport((host,port))
while True:
try:
passW = raw_input("\nEnter the SiteServer weekly password: ")
password = passW
username = 'gilbert'
nport = str(port)
print '\nEstablishing SFTP connection to: {}:{} ...'.format(host,port)
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
print 'Authorization Successful!!!'
log_names = ("/var/log/apache2/access.log",
"/var/log/apache2/error.log",
"/var/opt/smartmerch/log/merch_error.log",
"/var/opt/smartmerch/log/merch_event.log",
"/var/opt/smartmerch/log/server_sync.log")
#call search function here?
#for log_file, local_name in log_names.iteritems():
# sftp.get(log_file, local_name)
#sftp.close()
#transport.close()
break
except:
print "\nAuthorization Failed!!!"
Here is the function (in the same class) that I want to call:
def do_search(self, line):
print '\nCurrent dir: '+ os.getcwd()
userpath = raw_input("\nPlease enter a path to search (only enter folder name, eg. SQA\log): ")
directory = os.path.join("c:\\",userpath)
os.chdir(directory)
print "\n SEARCHES ARE CASE SENSITIVE"
print " "
line = "[1]Single File [2]Multiple Files [3]STATIC HEX"
col1 = line[0:14]
col2 = line[15:32]
col3 = line[33:46]
print " " + col1 + " " + col2 + " " + col3
print "\nCurrent Dir: " + os.getcwd()
searchType = raw_input("\nSelect type of search: ")
if searchType == '1':
logfile = raw_input("\nEnter filename to search (eg. name.log): ")
fiLe = open(logfile, "r")
userString = raw_input("\nEnter a string name to search: ")
for i,line in enumerate(fiLe.readlines()):
if userString in line:
print "String: " + userString
print "File: " + os.join(directory,logfile)
print "Line: " + str(i)
break
else:
print "%s NOT in %s" % (userString, logfile)
fiLe.close()
elif searchType =='2':
print "\nDirectory to be searched: " + directory
#directory = os.path.join("c:\\","SQA_log")
userstring = raw_input("Enter a string name to search: ")
userStrHEX = userstring.encode('hex')
userStrASCII = ''.join(str(ord(char)) for char in userstring)
regex = re.compile(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII )))
choice = raw_input("1: search with respect to whitespace. 2: search ignoring whitespace: ")
if choice == '1':
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root, file))
for i,line in enumerate(f.readlines()):
result = regex.search(line)
if result:
print "\nLine: " + str(i)
print "File: " + os.path.join(root,file)
print "String Type: " + result.group() + '\n'
f.close()
re.purge()
if choice == '2':
regex2 = re.compile(r'\s+')
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root, file))
for i,line in enumerate(f.readlines()):
result2 = regex.search(re.sub(regex2, '',line))
if result2:
print "\nLine: " + str(i)
print "File: " + os.path.join(root,file)
print "String Type: " + result2.group() + '\n'
f.close()
re.purge()
elif searchType =='3':
print "\nDirectory to be searched: " + directory
print " "
#directory = os.path.join("c:\\","SQA_log")
regex = re.compile(r'(?:3\d){6}')
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root,file))
for i, line in enumerate(f.readlines()):
searchedstr = regex.findall(line)
ln = str(i)
for word in searchedstr:
print "\nString found: " + word
print "Line: " + ln
print "File: " + os.path.join(root,file)
print " "
logfile = open('result3.log', 'w')
f.close()
re.purge()
self.do_search(linenumber)
That is all.
Methods are invoked via the object that has them.
self.do_search(...)

Categories