unexpected EOF while looking for matching `'': What does this mean? - python

these are the error messages I am receiving from the terminal when I run add_user.py
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
After some reading online I am led to believe that these errors are thrown when I am missing a matching parenthesis or quotation mark?I have looked through the file several times but since it has been a few hours, I might just be looking straight over the error. If it is not a missing quotation mark or parenthesis, please explain what might be causing the issue so I can fix it. Thanks to all who help!
import csv
import os
filename = "/root/Downloads/linux_users.csv"
def create_username(aList):
if (len(aList) < 2):
print("INVALID RECORD")
else:
tokens = list(aList[2])
username = tokens[0].lower() + aList[1].lower()
return username
with open(filename) as f_handle:
csv_reader = csv.reader(f_handle)
next(csv_reader)
userList = []
groupList = []
recordCopy = []
rep = 0
tick = True
for record in csv_reader:
if (record[7] == ""):
record.remove(record[7])
for data in record:
if (data == ""):
print("ERROR: MISSING INFORMATION. USER ID: " + record[0] + " HAS NOT BEEN ADDED")
tick = False
if ((record[6] not in groupList) and (tick == True)):
groupList.append(record[6])
if (tick == True):
username = create_username(record)
if (username in userList):
username += str(rep)
rep += 1
userList.append(username)
recordCopy.append(record)
else:
tick = True
for group in groupList:
os.system("groupadd " + group)
print("GROUP: " + group + " HAS SUCCESSFULLY BEEN CREATED")
i = 0
for record in recordCopy:
if (record[5] == "ceo"):
os.system("adduser " + userList[i] + " -g " + record[6] +
" -d /home/" + record[5] + " -s /bin/csh -u " + record[0] + " -p password")
os.system("passwd -e " + userList[i])
else:
os.system("adduser " + userList[i] + " -g " + record[6] +
" -d /home/" + record[5] + " -s /bin/bash -u " + record[0] + " -p password")
os.system("passwd -e " + userList[i])
i += 1
print("USER: " + record[0] + " HAS SUCCESSFULLY BEEN ADDED")

Related

The Invisible Invalid Syntax

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. '''

error sqlite3.OperationalError: no such column: false

I am getting this error sqlite3.OperationalError: no such column: false. I tried searching, but there seems to be no clear explanation and solution to this error for a newbie like me.
Please help.
def getViolationsFromCam(self, cam, cleared=False):
cur = self.con.cursor()
command = "SELECT camera.location, cars.id, cars.color, cars.first_sighted, cars.license_image, " \
" cars.license_number, cars.car_image, cars.num_rules_broken, cars.owner," \
" rules.name, rules.fine, violations.time, rules.id" \
" FROM violations, rules, cars, camera" \
" where rules.id = violations.rule" \
" and cars.id = violations.car" \
" and violations.camera = camera.id"
if cam is not None:
command = command + " and violations.camera = '" + str(cam) + "'"
if cleared:
command = command + " and violations.cleared = true"
else:
command = command + " and violations.cleared = false"
cur.execute(command)

how to telnet huawei switch with python script?

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`

Attempting to find Cooccupancy using a custom python script

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'")

Calling one module into another module

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

Categories

Resources