I have two python modules called main.py and black.py :
Main.py content as follows :
import os,sys,string,time
import subprocess,commands,re
import random
import black
class bcolors:
BOLD = '\033[1m'
UNBOLD = '033[0m'
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def disable(self):
self.BOLD = ''
self.UNBOLD = ''
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
def print_menu():
#subprocess.call("tput clear")
print " "
#print bcolors.OKBLUE + (35 * '-') + bcolors.OKBLUE
print bcolors.OKBLUE + '\t\t\t\t' + (52 * '*') + bcolors.OKBLUE
print ("\t\t\t\t\t\tM A I N - M E N U")
print '\t\t\t\t' + (52 * '*')
print ("\t\t\t\t 0. Enter POD Name(s).")
print ("\t\t\t\t 1. QUIT")
print '\t\t\t\t' + (52 * '*') + bcolors.ENDC
is_valid=0
while not is_valid:
try :
choice = int ( raw_input('Enter your choice [0-24] : ') )
is_valid = 1
except ValueError, e :
print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
return choice
########## M A I N #####################
rUser=commands.getoutput("id -un").strip()
if rUser != "oracle":
print bcolors.FAIL + " Login as mc_admin to run the script. Exiting .." + bcolors.ENDC
exit ()
else:
os.system("tput clear")
choice = print_menu()
###################
global podList #
podList = None #
###################
while choice >= 0 and choice < 1:
if choice == 0:
pPODName()
black.blackout()
and black.py content as follows:
def blackout():
def pPODName():
global podList
podList = str(raw_input('Enter pipe separated list of PODS : ')).upper().strip()
if podList:
try:
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -p " + "\"" + podList + "\""
prodP = commands.getoutput(cmd).strip()
if prodP:
print bcolors.FAIL + "Production Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + prodP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -t " + "\"" + podList + "\""
stagP = commands.getoutput(cmd).strip()
if stagP:
print bcolors.FAIL + "Stage/Test Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + stagP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -d " + "\"" + podList + "\""
devP = commands.getoutput(cmd).strip()
if devP:
print bcolors.FAIL + "Dev/Upgrade Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + devP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -i " + "\"" + podList + "\""
intstgP = commands.getoutput(cmd).strip()
if intstgP:
print bcolors.FAIL + "Internal Staging Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + intstgP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -r " + "\"" + podList + "\""
prtnP = commands.getoutput(cmd).strip()
if prtnP:
print bcolors.FAIL + "Partner Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + prtnP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -s " + "\"" + podList + "\""
stbyP = commands.getoutput(cmd).strip()
if stbyP:
print bcolors.FAIL + "DR/Standby Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + stbyP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -u " + "\"" + podList + "\""
unalloP = commands.getoutput(cmd).strip()
if unalloP:
print bcolors.FAIL + "Unallocated Pods [Status: Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + unalloP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -l " + "\"" + podList + "\""
trlP = commands.getoutput(cmd).strip()
if trlP:
print bcolors.FAIL + "Trial Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + trlP + bcolors.ENDC
except OSError:
print bcolors.FAIL + "Could not invoke Pod Details Script. " + bcolors.ENDC
podList = vPodName(podList)
print bcolors.FAIL + "\nYou Have Entered PodList as: " + podList + "\n" + bcolors.ENDC
uResp = str(raw_input('Do You Want To Continue [YES|Y|NO|N] : ')).upper().strip()
#if uResp == "NO" or uResp == "N":
if uResp != "YES" and uResp != 'Y':
pPODName ()
if __name__ == '__main__':
blackout()
I want black.py module to be called in main.py but when I am running main.py I am getting the following error:
[oracle#localhost tmp]$ ./main.py
****************************************************
M A I N - M E N U
****************************************************
0. Enter POD Name(s).
1. QUIT
Enter your choice [0-24] : 0
Traceback (most recent call last):
File "./main.py", line 131, in <module>
pPODName()
NameError: name 'pPODName' is not defined
pPODName has not been defined as far as main.py can tell.
Firstly
pPODName is defined within another function, so only that function is aware of it. This is referred to as being in local scope. Basically anything defined within a function is only accessible to that function, and nothing else.
For an example:
def test():
def test_local():
return 3
return test_local()
Running the function test gives you
>>> test()
3
However running the function test_local
>>> test_local()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test_local' is not defined
Secondly
Secondly, when importing modules, you need to either qualify them with the module name, like you have done with black.blackout(), of you need to use:
from black import *
Although personally I don't like that, it makes it hard to see where methods are coming from.
Fix
For main.py to be able to call pPODName, it must be defined within the module as a whole, e.g.:
def blackout()
#do stuff here
def pPODNAME()
#do other stuff here
#note the indentation level is the same as blackout
and you must call it with
black.pPODName()
From main.py
You have some programming hierarchy level mistake
why pPODName is inner function of blackout ?
and has James said- if you are using outer and inner function the outer needs to call the inner.
I suggest you to use regular function in black.py
blackout function does nothing except containing the pPODName so you don't need it
Shlomy
Related
I am running this code to list the IP addresses on my network along with the mac addresses but i ran into this problem. it says invalid syntax but i can't seem to find what is wrong with it
I've tried removing spaces and replacing them with tabs but it doesn't fix it. i also tried moving them one up or down but still doesn't work. Any help?
The Whole code:
from getmac import get_mac_address
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
minr = int(input("Starting Ip: "))
maxr = int(input("Ending Ip: "))
while True:
for num in range(minr, maxr + 1): #plus one is to include the last digit entered
ip = "192.168.2." + str(num)
from getmac import getmac
exit_code = os.system("ping -n 1 -w 1 " + ip + " > nul") # Windows
#exit_code = os.system("ping -c 1 -W 1 " + ip + " > /dev/null") # Linux
getmac.PORT = 44444 # Default: 55555
if exit_code == 0:
print(ip, bcolors.OKGREEN + "ONLINE" + bcolors.ENDC + get_mac_address(ip=ip, network_request=True)
elif (ip == '192.168.2.' + str(maxr + 1) and exit_code == 0):
print('192.168.2.' + str(maxr), bcolors.OKGREEN + "ONLINE" + bcolors.ENDC + get_mac_address(ip=ip, network_request=True))
print("")
print(bcolors.HEADER + "Beginning" + bcolors.ENDC)
print("")
elif (ip == '192.168.2.' + str(maxr)):
print('192.168.2.' + str(maxr), bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
print("")
print(bcolors.HEADER + "Refreshed" + bcolors.ENDC)
print("")
else:
print(ip, bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
I am supposed to see the IP addressees along with the mac but i get this error code:
$ python test.py
File "test.py", line 34
elif (ip == '192.168.2.' + str(maxr + 1) and exit_code == 0):
^
SyntaxError: invalid syntax
I just forgot to add the ) at the end of the line above. Thanks to #depperm he showed me my mistake. Where it says ''' print(ip, bcolors.OKGREEN + "ONLINE" + bcolors.ENDC + get_mac_address(ip=ip, network_request=True)
at the end of the bracket add one more. '''
I want to telnet huawei switch with python script to read some basic staff like "display int brief" result. I know basic huawei command and some programming.
I can telnet cisco router with python script.
Here is my attempt so far
import telnetlib
import datetime
now = datetime.datetime.now()
host = "myhost" # your router ip
username = "user" # the username
password = "pass"
tn = telnetlib.Telnet(host,23,6)
tn.read_until("Username:")
tn.write(username+"\n")
tn.read_until("Password:")
tn.write(password+"\n")
tn.write("display int description"+"\n")
#tn.write("sh run"+"\n")
tn.write("quit"+"\n")
output = tn.read_all()
fp = open("sw_hu.txt","w")
fp.write(output)
fp.close()
I would use pexpect library then open connection with pexpect.spawn('telnet ip_address') module documentation is great start. If you now commands then it is mostly combination off sendline, expect and before.
child = pexpect.spawn ('telnet %s' % dev_name)
try:
i = child.expect_exact(['Password:', 'Username:'])
except (pexpect.EOF, pexpect.TIMEOUT):
return False
if i == 1:
child.sendline(user_name)
child.expect_exact('Password:')
child.sendline(passw)
else:
child.sendline(passw)
if child.expect_exact(['>', 'Wrong', pexpect.TIMEOUT], timeout=5):
child.close()
return False
child.sendline('sup')
i = child.expect_exact(['Password:', '>', 'Unknown', 'not set'])
if i == 1:
child.sendline('')
elif i == 2 or i == 3:
child.close()
return False
else:
child.sendline(ena)
if child.expect_exact(['>', 'Password', 'failed']):
child.close()
child.sendline('tftp %s put %s %s.backup.txt' % (TFTP, conf_name, name))
child.expect_exact(['>', 'successfully'])
if 'Unable' in child.before:
....
....
Edit: Added partial example to backup config (it is python 2.x and old Huawei router)
if w['router_type'] == "cisco":
tn.read_until("Username:")
tn.write(user.encode('ascii')+"\n"
#tn.write(user +"\n")
if password:
tn.read_until("Password:")
tn.write(password.encode("ascii") + "\n")(indent)
tn.write("terminal length 0\n")
tn.write("show version\n")
tn.write("show running-config view full\n")
tn.write("exit\n")
tn_output = tn.read_all()
print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
flag = 1
if w['router_type'] == "huawei":
tn.read_until("Username:")
tn.write(user + "\n")
if password:
tn.read_until("Password:")
tn.write(password + "\n")
tn.write("screen-length 0 temporary\n")
tn.write("dis version\n")
tn.write("dis current-configuration\n")
tn_output = tn.read_until("return")
tn.write("quit\n")
print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
flag = 1
if w['router_type'] == "MAIPU":
tn.read_until("login:")
tn.write(user + "\n")
if password:
tn.read_until("password:")
tn.write(password + "\n")
tn.write("more off\n")
tn.write("show version\n")
tn.write("show running\n")
tn.write("logout\n")
tn_output = tn.read_all()
flag = 1
print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
print ("\n Count: " )+ str(v_count) + ("---\n")
if flag:
if v_count==0:
saveoutput = open ("BACKUP/" + HOST + ".txt" , "w")
saveoutput.write(tn_output)
print ("Saving new file ") + HOST + ("......")
elif v_count == 1:
previous_file = open("BACKUP/" + HOST + ".txt")
temp_file = previous_file.read()
if str(temp_file) != str(tn_output):
saveoutput = open ("BACKUP/" + HOST + "_v2.txt" , "w")
saveoutput.write(tn_output)`enter code here`
print ("Saving new file " )+ HOST + ("......")
elif v_count > 1:
previous_file = open("BACKUP/" + HOST + "_v" + str(v_count) + ".txt")
temp_file = previous_file.read()
if str(temp_file) != str(tn_output):
saveoutput = open ("BACKUP/" + HOST + "_v" + str(v_count + 1) + ".txt" , "w")
print ("Saving new version of file ") + HOST + ("......")`enter code here`
I am trying to get the System User's Login Time using Python 3.7. I have tried win32net and platform module for Python but, functions are not defined in platform module and Win32net is not compatible with Python 3 and more. I have tried following code:
import platform
platform.uname()
import platform
os_name = platform.uname()[0].lower()
if os_name == "windows":
get_win_login_time()
elif os_name.endswith("nix"):
get_nix_login_time()
Try These ( install win32com.client and subprocess modules first ):
import win32com.client, time
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_NetworkLoginProfile")
def Convert_to_human_time(dtmDate):
strDateTime = ""
if dtmDate[4] == 0:
strDateTime = dtmDate[5] + '/'
else:
strDateTime = dtmDate[4] + dtmDate[5] + '/'
if dtmDate[6] == 0:
strDateTime = strDateTime + dtmDate[7] + '/'
else:
strDateTime = strDateTime + dtmDate[6] + dtmDate[7] + '/'
strDateTime = strDateTime + dtmDate[0] + dtmDate[1] + dtmDate[2] + dtmDate[3] + " " + dtmDate[8] + dtmDate[9] + ":" + dtmDate[10] + dtmDate[11] +':' + dtmDate[12] + dtmDate[13]
return strDateTime
for objItem in colItems:
if objItem.Name is not None:
print("Name: " + str(objItem.Name))
if objItem.LastLogon is not None:
print("Last Logon (Normal Format): " + str(objItem.LastLogon))
print("Last Logon (Human Readable Format): " + Convert_to_human_time(objItem.LastLogon))
if objItem.LastLogoff is not None:
print("Last Logoff (Normal Format): " + str(objItem.LastLogoff))
print("Last Logoff (Human Readable Format): " + Convert_to_human_time(objItem.LastLogoff))
if objItem.LogonHours is not None:
print("Logon Hours: " + str(objItem.LogonHours))
if objItem.LogonServer is not None:
print("Logon Server: " + str(objItem.LogonServer))
if objItem.NumberOfLogons is not None:
print("Number Of Logons: " + str(objItem.NumberOfLogons))
Another way :
from subprocess import check_output
import sys
get_result = check_output("wmic netlogin get name, fullname, lastlogon", shell=True, stderr=False)
print(get_result)
clean_result = str(get_result).lstrip("b'").rstrip("'").replace("\\r\\r\\n", "\n").replace('\n\n', '\n').split('\n')[2:-1]
for items in clean_result:
print(items.lstrip().rstrip())
Good Luck ...
This script was created by an ex-lab member that was quite a bit more adapt at Python scripting than I am.
I am attempting to find Cooccupancy between annotated peaks in "exon" regions of the entire human h19 genome. However, after trying to get this to run for about an hour I am looking for help.
Here is the script:
#!/usr/bin/python
import math
import sys
import re
import csv
import MySQLdb
import itertools
import argparse
# format for execution: ./findCooccupancy.py <loci file> <comma separated list of marks to check> <window size> <outputfile>
# example: ./findCooccupancy.py AllGenes.txt PolII-ChIP,KAP1-ChIP,Hexim 150 output.txt
# format of loci file:
# chr2 12345678 12345900 GENEA 1 +
# chr4 987654321 98765000 GENEB 1 -
# etc...
locifile = sys.argv[1]
marks = sys.argv[2]
window = int(sys.argv[3])
outputfile = sys.argv[4]
loci = list(csv.reader(open(locifile, 'rb'),delimiter='\t'))
#loci = list(itertools.chain.from_iterable(loci))
db = MySQLdb.connect(host="localhost",user="snrnp",passwd="snrnp",db="snrnp")
cur = db.cursor()
cntdict = {}
for mark in marks.split(","):
cntdict[mark] = []
counter = 1
for locus in loci:
print "Working on line# " + str(counter)
counter += 1
if str(locus[5]) == "+":
exon = locus[1]
else:
exon = locus[2]
for mark in marks.split(","):
# this is incredibly dirty. sorry. I don't have time to do this better
if mark == 'PolII-ChIP':
cur.execute("select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and (abs(summit - " + str(exon) + ") < " + str(window) + ")")
#print "select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and (abs(summit - " + str(exon) + ") < " + str(window) + ")"
else:
cur.execute("select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and ((chr_start < " + str(exon) + " and chr_end > " + str(exon) + ") or (abs(chr_start - " + str(exon) + ") < " + str(window) + ") or (abs(chr_end - " + str(exon) + ") < " + str(window) + "))")
#print "select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and ((chr_start < " + str(exon) + " and chr_end > " + str(exon) + ") or (abs(chr_start - " + str(exon) + ") < " + str(window) + ") or (abs(chr_end - " + str(exon) + ") < " + str(window) + "))"
cnt = cur.fetchone()[0]
if cnt > 0:
cntdict[mark].append(",".join(locus))
convertedlist = []
for key in cntdict.keys():
convertedlist.append(cntdict[key])
intersectlist = set(convertedlist[0]).intersection(*convertedlist[1:])
for key in cntdict.keys():
print str(key) + " hits: " + str(len(cntdict[key]))
print "\nTotal Intersection Count: " + str(len(intersectlist))
with open(outputfile, 'w') as outputwriter:
for line in intersectlist:
outputwriter.write(line + "\n")
This is the command line that I have been using:
./findCooccupancy.py ~/code/snRNP/analysis/from\ sequencing/KEC_Project/Pol-IIAnnotatedPeaksGenome.txt PolII-ChIP 150 KECExonOccupancy.txt
This is the latest error message I have received:
Working on line# 1
Traceback (most recent call last):
File "./findCooccupancy.py", line 41, in <module>
cur.execute("select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and (abs(summit - " + str(exon) + ") < " + str(window) + ")")
File "/Library/Python/2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/Library/Python/2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1054, "Unknown column 'Start' in 'where clause'")
I have a Executable named learn after compiling my program vv.c in linux.I am using Tkinter (python-Tk) for making My GUI.But When running my executable code.It reached a error message "sh :1 : learn :not found " where -t -c -b are parametes passing to executable.
else:
if self.binaryFeature == 0:
cmd = "learn" + "-t " + self.type + " -c "\
+ self.C + " " + self.e2.get() + " " + self.e3.get()
else:
cmd = "learn" + "-t " + self.type + " -c "\
+ self.C + " -b 1 " + self.e2.get()\
+ " " + self.e3.get()
output_string = commands.getoutput(cmd)
self.text.insert(INSERT, output_string+"\n","CprogramOutput")
is it any error in commands for executing ?please help me ..thanks
You need to put a space before "-t":
cmd = "learn" + " -t " + self.type + " -c "\
+ self.C + " " + self.e2.get() + " " + self.e3.get()
currently the shell evaluates the command as learn-t rather than learn -t.