Python 2.7.11 getopt doesn't read the argument - python-2.7

In Python 2.7.13
We have the following python code to take the command line argument:
import sys
import csv
import os
import sys, getopt
import pandas as pd
print('Python version ' + sys.version)
print('Pandas version ' + pd.__version__)
def main():
SERVER_NAME=''
PORT_NAME=''
PASSWORD=''
try:
opts, args = getopt.getopt(sys.argv[1:],"hs:p:x:",["server=","port=","password="])
except getopt.GetoptError:
print 'help'
sys.exit(2)
for o, a in opts:
if o == '-h':
print '\n'+'-s / --server (required)'
print '\n'+'-p or --port (required)'
print '\n'+'-x or --password (required)'
sys.exit()
elif o in ("-s", "--server"):
SERVER_NAME = a
elif o in ("-p", "--port"):
PORT_NAME = a
elif o in ("-x", "--password"):
PASSWORD = a
else:
assert False, "No command line option. To see the options, plese use -h"
if __name__ == "__main__":
main()
print SERVER_NAME
dbServer=SERVER_NAME
However, when running the above code in the command line:
python test.py -s AAA -p BBB -x CCC
the following error will show up:
print SERVER_NAME
NameError: name 'SERVER_NAME' is not defined
Could any guru enlighten if anything is wrong here? Thanks.

SERVER_NAME is defined as a variable local to the main() function, si it is not visible in the global scope (the lines at the bottom of your code.
You could either make SERVER_NAME a global variable or move the code after the call to main() into main(). My preference would be the latter; when I write code with a CLI like this, I don't have any code after calling main() (I often have global setup code before that call, but none of that depends on what happens in the main function)
Here is what I mean by 'moving code into main':
dbServer = ''
def main():
global dbServer
SERVER_NAME=''
PORT_NAME=''
PASSWORD=''
try:
opts, args = getopt.getopt(sys.argv[1:],"hs:p:x:", ["server=","port=","password="])
except getopt.GetoptError:
print 'help'
sys.exit(2)
for o, a in opts:
if o == '-h':
print '\n'+'-s / --server (required)'
print '\n'+'-p or --port (required)'
print '\n'+'-x or --password (required)'
sys.exit()
elif o in ("-s", "--server"):
SERVER_NAME = a
elif o in ("-p", "--port"):
PORT_NAME = a
elif o in ("-x", "--password"):
PASSWORD = a
else:
assert False, "No command line option. To see the options, plese use -h"
print SERVER_NAME
dbServer=SERVER_NAME
if __name__ == "__main__":
main()

Related

awk command in subprocess.Popen - Getting Error

I am trying this code:This code work fine and gave me the output what i need .
import os,sys
import sitenamevalidation
import getpass
import subprocess
site_name = sys.argv[1]
def get_location(site_name):
site_name_vali = sitenamevalidation.sitenamevalidation(site_name)
if site_name_vali == True:
pass
else:
print("Sitename should be in this format [a-z][a-z][a-z][0-9][0-9] example abc54 or xyz50")
sys.exit(0)
site = site_name[:3].upper()
user =getpass.getuser()
path = os.path.join('/home/',user,'location.attr')
if os.path.exists(path) == True:
pass
else:
print("Not able to find below path "+path)
#p1 = subprocess.Popen(['awk', '/site/{getline; print}' , path] ,stdout=subprocess.PIPE)
p1 = subprocess.Popen(['awk', '/ABC/{getline; print}' , path] ,stdout=subprocess.PIPE)
output=p1.communicate()
print str(output[0].strip().lower())
if __name__ == "__main__":
get_location(site_name)
Main issue is if i use this below command
p1 = subprocess.Popen(['awk', '/ABC/{getline; print}' , path] ,stdout=subprocess.PIPE)
where ABC is static value in path it work fine and give me desired output but i wanted the value which user will enter (site in my code). When i am doing this
p1 = subprocess.Popen(['awk', '/site/{getline; print}' , path] ,stdout=subprocess.PIPE)
It is looking for site in that file which is not there.I want the value of site variable to go in that command rather the site itself.Tried different by putting quote , double quote but nothing seem to be working.

Paramiko hanging when encounters missing output

Paramiko Script is hanging, attempting to ssh through a list of IP address and execute a few commands to extract information that may or may not be there. For example if i was to implement a uname -a it should reveal the hostname, however if the next server in the list doesn't have a hostname then it seems the script is hanging.
import paramiko
import sys
import io
import getpass
import os
import time
# ***** Open Plain Text
f = open("file.txt")
# ***** Read & Store into Variable
hn=(f.read().splitlines())
f.close()
# ***** Credentials
username = raw_input("Please Enter Username: ")
password = getpass.getpass("Please Enter Passwod: ")
# ***** SSH
client=paramiko.SSHClient()
def connect_ssh(hn):
try:
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hn, 22, username, password, look_for_keys=False, allow_agent=False)
print 'Connection Attempting to: '+(hn)
channel = client.get_transport().open_session()
channel.invoke_shell()
#print "CMD
#channel.send("CMD"+"\n")
channel.send("command"+"\n")
CMD = (channel.recv(650000))
print (CMD)
except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e)
try:
channel.close()
except:
pass
# *****Create Loop through input.txt
for x in hn:
connect_ssh(x)

python2.7 netcat program running with subprocesses

I am trying to make a script to mimic netcat and it kinda runs but i don't get the result i'm meant to, when trying to debug it i managed to do a bit but after days of searching and trial and errors i am at a loss at how to fix the issue. This is my whole code:
import sys
import socket
import getopt
import threading
import subprocess
import os
# define the global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "BHP Net Tool"
print "Usage: netcat2.py -t target_host -p port"
print "-l --listen - listen on [host]:[port] for incoming
connections"
print "-e --execute=file_to_run - execute the given file upon receiving
a connection"
print "-c --command - initialize a command shell"
print "-u --upload=destination - upon receiving connection upload a
file and wrtie to [destination]"
print "Examples: "
print "netcat2.py -t 192.168.0.1 -p 5555 -l -c"
print "netcat2.py -t 192.168.0.1 -p 5555 -l -u=C:\\target.exe"
print "netcat2.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEFGHI' | ./netcat2.py -t 192.168.0.1 -p 135"
sys.exit(0)
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
# read the commandline option
try:
opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu", ["help",
"listen", "execute", "target", "port", "command", "upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o, a in opts:
if o in ("-h", "--help"):
usage()
elif o in ("-l", "--listen"):
listen = True
elif o in ("-e", "--execute"):
execute = a
elif o in ("-c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target = a
elif o in ("-p", "--port"):
port = int(a)
else:
assert False, "Unhandled Option"
# are we going to listen or just send data from stdin?
if not listen and len(target) and port > 0:
# read in the line from the commandline
# this will block, so send CTRL-D if not sending input
# to stdin
line = sys.stdin.readline()
print (line)
# send data off
client_sender(line)
# we are going to listen and potentially
# upload things, execute commands, and drop a shell back
# depending on our command line options above
if listen:
server_loop()
def client_sender(line):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# connect to our target host
client.connect((target, port))
if len(line):
client.send(line)
while True:
# now wait for data back
recv_len = 1
response = ""
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response += data
if recv_len < 4096:
break
print "response"
# wait for more input
line = raw_input("")
line += "\n"
# send it off
client.sendline()
except:
print "[*] Exception! Exiting."
# tear down the connection
client.close()
def server_loop():
global target
# if no target is defined, we listen on all interfaces
if not len(target):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
# spin off a thread to handle out new client
client_thread = threading.Thread(target=client_handler, args=
(client_socket,))
client_thread.start()
def run_command(command):
# trim the newline
command = command.rstrip()
# run the command and get the output back
try:
with open(os.devnull, 'w') as devnull:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execite command. \r\n"
# send the output back to the client
return output
def client_handler(client_socket):
global upload
global execute
global command
# check for upload
if len(upload_destination):
# read in all of the bytes and write to out destination
file_line = ""
# keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_line += data
# now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination, "wb")
file_descriptor.write(file_line)
file_descriptor.close()
# acknowledge that we wrote the file out
client_socket.send("Succesfully saved file to %s\r\n" %
upload_destination)
except:
client_socket.send("Failed to save file to %s\r\n" %
upload_destination)
# check for command execution
if len(execute):
# run the command
output = run_command(execute)
client_socket.send(output)
# now we go into another loop if a command shell was requested
if command:
while True:
# show a simple prompt
client_socket.send("<BHP:#> ")
# now we receive until we see a linefeed (enter key)
cmd_line = ""
while "\n" not in cmd_line:
cmd_line += client_socket.recv(1024)
# send back the command output
response = run_command(cmd_line)
# send back the response
client_socket.send(response)
main()
when i run it, and close it with CTRL+D it exits and when i close the terminal i get this message in localhost:
<BHP:#> Failed to execite command.
<BHP:#>
if anyone can help me fix this or even point me in the right direction i'd really appreciate it :), i'm trying to run this in python 2.7

Make Python module callable

need some help making the below a callable object for another script e.g scrape.run()
I'm not sure where to start any pointers?
scrape.py
from clint.textui import puts, colored
import subprocess, sys
from datetime import datetime
from time import sleep as sleep
today = datetime.now().strftime("%H:%M:%S")
multimon_ng = subprocess.Popen("rtl_fm -A lut -s 22050 -f 148.81250M | multimon-ng -t raw -a FLEX -f alpha /dev/stdin",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
while True:
try:
nextline = multimon_ng.stdout.readline()
if not nextline:
pass
else:
try:
flex, mdate, mtime, bitrate, other, capcode, o2, msg = nextline.split(" ", 7)
except ValueError:
print "invalid line", nextline
else:
puts(colored.yellow(capcode), newline=False)
puts(" [", newline=False)
puts(colored.green(mdate + " " + str(datetime.now().strftime('%H:%M'))), newline=False)
puts(" ]", newline=False)
puts(msg)
except KeyboardInterrupt:
print "exit"
multimon_ng.poll()
Add this to the bottom of the script.
if __name__ == "__main__":
function_you_wish_to_call_here()
Anything under the if statement will run when you call the script directly.

how to run python script with crontab with proxy

I am trying to run a python script from bash script to upload files to a website using crontab. The script runs from terminal but doesn't work from crontab and the error is
"Error: <urlopen error [Errno -2] Name or service not known>"
The python script is:
#!/usr/bin/env python
from ConfigParser import ConfigParser
from mechanize import Browser, RobustFactory
import base64
from os.path import basename
import sys
import os
print(os.environ)
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Error: 1 argument needed"
sys.exit(1)
#DATA FROM CFG FILE
url = "http:website"
cfn = "absolute_path/upload.cfg"
cfg = ConfigParser()
try:
cfg.read(cfn)
usr = cfg.get('Auth', 'user')
pwd = cfg.get('Auth', 'pass')
except Exception, e:
print "Error:", e
sys.exit(1)
if not usr or not pwd:
print "Error: username or password not valid."
sys.exit(1)
filename = sys.argv[1]
try:
br = Browser(factory=RobustFactory())
br.addheaders.append(('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (usr, pwd))))
br.open(url)
br.select_form(nr=1)
br.form.add_file(open(filename, 'rb'), 'text/plain', basename(filename))
br.submit()
print "File '%s' successfully uploaded" % filename
sys.exit(0)
except Exception, e:
print "Error:", e
sys.exit(1)
When I try to "print(os.environ)" in python script in the case of manual run and using crontab:
with crontab :
"{'MAILTO': '/var/mail/envclim', 'LANG': 'en_US.UTF-8', 'SHELL': '/bin/sh', 'XDG_RUNTIME_DIR': '/run/user/1000', 'SHLVL': '2', 'PYTHONPATH': '/usr/lib/python2.7/site-packages:/usr/lib/python2.7/site-packages/', 'OLDPWD': '/home/envclim/upload_sdswas', 'PWD': '/home/envclim/upload_sdswas/upload_scripts', 'LOGNAME': 'envclim', 'USER': 'envclim', 'HOME': '/home/envclim', 'PATH': '/bin:/usr/bin:/usr/local/bin:/usr/local/CDO/bin', 'XDG_SESSION_ID': '6', '_': '/usr/bin/python'}"
but in the manual case , there is the proxy, as the following:
{'HTTP_PROXY': 'http://10.51.51.51:80/', 'KDE_IS_PRELINKED': '1', 'ALL_PROXY': 'socks://10.51.51.51:80/', 'NO_PROXY': 'localhost,127.0.0.0/8,::1', 'GJS_DEBUG_OUTPUT': 'stderr', 'http_proxy': 'http://10.51.51.51:80/', 'FTP_PROXY': 'http://10.51.51.51:80/',----------}
In crontab, I add :
SHELL=/bin/sh
PATH=/bin:/usr/bin
PYTHONPATH=/usr/lib/python2.7/site-packages
MAILTO=/var/mail/envclim
I am using fedora19. I tried to disabled proxy, but the script didn't work at all.
please, can anyone solve this problem?
Thanks in advance
Zeinab
Thanks alot for your comments, I solved this problem by adding these lines in crontab:
PYTHONPATH=/usr/lib/python2.7/site-packages
HTTP_PROXY=http://10.51.51.51:80/
and in the bash file that used to run the python script:
export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/site-packages/
export LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:/usr/local/usr/lib