Python Scripts: Difference between revisions
Content added Content deleted
Line 241: | Line 241: | ||
import paramiko |
import paramiko |
||
import sys |
import sys |
||
import re |
|||
import time |
|||
from bin import NitroRestClient |
from bin import NitroRestClient |
||
# Netscaler Parameters |
|||
nsip = "10.107.88.78" |
nsip = "10.107.88.78" |
||
nsun = "nsroot" |
nsun = "nsroot" |
||
Line 248: | Line 251: | ||
nssrv = "Ubuntu_Server" |
nssrv = "Ubuntu_Server" |
||
# Server Parameters |
|||
#srvip = "10.107.88.93" |
|||
srvip = "10.107.88.93" |
|||
srvun = "aman" |
|||
srvpwd = "Passion@123" |
|||
# Loop Logic variables |
|||
# Initial Server State, 0 = enabled, 1 = disabled |
|||
x = 1 |
|||
y = 0 |
|||
# Attempt SSH Connection |
# Attempt SSH Connection |
||
ssh = paramiko.SSHClient() |
ssh = paramiko.SSHClient() |
||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
||
ssh.connect( |
ssh.connect( srvip, username = srvun, password = srvpwd ) |
||
# Attempt instantiation of NitroRestClient |
# Attempt instantiation of NitroRestClient |
||
Line 275: | Line 280: | ||
# Main Program |
# Main Program |
||
try: |
|||
for i in range(100): |
|||
while True: |
|||
stdin, stdout, stderr = ssh.exec_command( 'top -bn2 | grep "Cpu(s)"' ) |
|||
output = stdout.read() |
|||
value = re.findall(r'([0-9]{3}.[0-9]|[0-9]{2}.[0-9]|[0-9].[0-9])\sid', output) |
|||
stat = output.split() |
|||
cpu = (100-float(value[1])) |
|||
⚫ | |||
cpu = (100-idle) |
|||
⚫ | |||
if cpu > 50: |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
if cpu < 50: |
|||
if |
if x == 1: |
||
⚫ | |||
time.sleep(5) |
|||
⚫ | |||
print("Server enabled") |
|||
Client.enablephysicalserver(normalizedservername) |
Client.enablephysicalserver(normalizedservername) |
||
x = 1 |
|||
y = 0 |
|||
else: |
|||
if y == 1: |
|||
print("Server remains disabled..") |
print("Server remains disabled..") |
||
time.sleep(5) |
|||
else: |
|||
⚫ | |||
⚫ | |||
time.sleep(1) |
|||
⚫ | |||
x = 0 |
|||
except KeyboardInterrupt: |
|||
⚫ | |||
print("Script Killed by user") |
|||
ssh.close() |
ssh.close() |
||
⚫ | |||
</pre> |
</pre> |
||
Revision as of 12:35, 11 November 2017
Calculator
#!/usr/bin/python #Define Function def calc(): operation = raw_input(''' Please type operator: + for addition - for subtraction * for multiplication / for division ''') #try: num1 = float(input('First Number: ')) num2 = float(input('Second Number: ')) #except: #print("Invalid Input") if operation == '+': add = num1 + num2 print("Addition is: %d" % int(add)) elif operation == '-': sub = num1 - num2 print("Subtraction is %d:" %int(sub)) elif operation == '*': mul = num1 * num2 print("Multiplication is %d:" %int(mul)) elif operation == '/': div = num1 / num2 print("Division is %.2f:" %float(div)) else: print("Invalid Operator") again() def again(): calc_again = raw_input(''' Do you want to calculate again? Please type Y for Yes or N for No. ''') if calc_again.upper() == "Y": calc() elif calc_again.upper() == "N": print('See you later on.. Bye') else: again() def welcome(): print(''' Welcome to My Calculator ''') #Call Function welcome() calc()
Add Routes to Remote Server
import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( '192.168.1.7', username = 'root', password = 'pwd@123' ) for x in range(1,256): for y in range(256): for z in range(256): for a in range(1): ssh.exec_command( "route add -net %d.%d.%d.%d netmask 255.255.255.0 gw 192.168.1.1 " %(x,y,z,a)) ssh.close()
Paramiko execute commands
Source: sebastiandahlgren.se
import paramiko import time import select import sys # NetScaler/Server Parameters host = '10.107.88.78' user = 'nsroot' passwd = 'pwd@123' cmd = 'show runningconfig' i = 1 # Try to connect to the host, Retry a few times if it fails. while True: print "Trying to connect to %s (%i/10)" % (host, i) try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( host, username = user, password = passwd ) print "Connected to %s" % host break except paramiko.AuthenticationException: print "Authentication failed when connecting to %s" % host sys.exit(1) except: print "Could not SSH to %s, waiting for it to start" % host i += 1 time.sleep(2) # If we could not connect within time limit if i == 10: print "Could not connect to %s. Giving up" % host sys.exit(1) # Send the command (non-blocking) stdin, stdout, stderr = ssh.exec_command( cmd ) # Wait for the command to terminate while not stdout.channel.exit_status_ready(): # Only print data if there is data to read in the channel if stdout.channel.recv_ready(): rl, wl, xl = select.select([stdout.channel], [], [], 0.0) if len(rl) > 0: # Print data from stdout print stdout.channel.recv(1024), # Disconnect from the host print "\nCommand done, closing SSH connection" ssh.close()
Docker add multiple servers remotely
import paramiko import time ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( '10.107.88.93', username = 'aman', password = 'pwd@123' ) for i in range(44400,44405): ssh.exec_command("docker run --name docker-nginx%d -p %d:8000 -d nginx" %(i,i)) print("Docker server created..") time.sleep(1) print("Done") ssh.close()
CPU check of Remote Server
import paramiko from terminalplot import plot ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( '10.107.88.93', username = 'aman', password = 'pwd@123' ) for i in range(10): stdin, stdout, stderr = ssh.exec_command( 'top -bn2 | grep "Cpu(s)"' ) output = stdout.read() stat = output.split() idle = float(stat[24]) cpu = (100-idle) print cpu ssh.close()
TCPDump
- Print captured packets
import subprocess as sub p= sub.Popen(('sudo', 'tcpdump', '-l'), stdout=sub.PIPE) for row in iter(p.stdout.readline, b''): print row.rstrip()
- Print Packet Length
import subprocess as sub import re try: p = sub.Popen(('sudo', 'tcpdump', '-l'), stdout=sub.PIPE) for row in iter(p.stdout.readline, b''): y = re.search('length (\d+)', row) if y: x = int(y.group(1)) if x !=0: print x except KeyboardInterrupt: print("User killed command.")
eSpeak Password
import os def check(): x = int(input("Input your password: ")) if (x == 1234): os.system("espeak 'correct password'") else: os.system("espeak 'wrong password'") def again(): check() again() check() again()
NetScaler NITRO REST Server Monitor using SSH
- Monitors CPU Utilization of Backend Server, Disables service if CPU Exceeds 50%
- Requires: NitroRestClient
import paramiko import sys import re import time from bin import NitroRestClient # Netscaler Parameters nsip = "10.107.88.78" nsun = "nsroot" nspwd = "pwd@123" nssrv = "Ubuntu_Server" # Server Parameters srvip = "10.107.88.93" srvun = "aman" srvpwd = "Passion@123" # Loop Logic variables x = 1 y = 0 # Attempt SSH Connection ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( srvip, username = srvun, password = srvpwd ) # Attempt instantiation of NitroRestClient try: Client = NitroRestClient.NitroRestClient(nsip, nsun, nspwd) except: print("Couldn't create Nitro Session, check username and password and network connectivity") sys.exit(1) # Check servername for validity try: normalizedservername = Client.servernamecheck(nssrv) except ValueError as e: print("Invalid server name was provided. Please check server name and try again.") sys.exit(2) # Main Program try: while True: stdin, stdout, stderr = ssh.exec_command( 'top -bn2 | grep "Cpu(s)"' ) output = stdout.read() value = re.findall(r'([0-9]{3}.[0-9]|[0-9]{2}.[0-9]|[0-9].[0-9])\sid', output) cpu = (100-float(value[1])) print cpu if cpu < 50: if x == 1: print("CPU is normal..") time.sleep(5) else: print("Server enabled") Client.enablephysicalserver(normalizedservername) x = 1 y = 0 else: if y == 1: print("Server remains disabled..") time.sleep(5) else: Client.disablephysicalserver(normalizedservername) print("Server disabled") time.sleep(1) y = 1 x = 0 except KeyboardInterrupt: print("Script Killed by user") ssh.close() sys.exit(0)
NetScaler NITRO REST Server Monitor using SNMP
- Monitors CPU Utilization of Backend Server, Disables service if Load Exceeds 0.50
- Requires: NitroRestClient
- Requires SNMP configured on Server & SNMP Utils installed on the PC where script is run.
import time import subprocess import sys import re from bin import NitroRestClient # Netscaler Parameters & Credentials nsip = "10.107.88.78" nsun = "nsroot" nspwd = "pwd@123" nssrv = "Ubuntu_Server" # Loop Logic variables x = 1 y = 0 # Attempt instantiation of NitroRestClient try: Client = NitroRestClient.NitroRestClient(nsip, nsun, nspwd) except: print("Couldn't create Nitro Session, check username and password and network connectivity") sys.exit(1) # Check servername for validity try: normalizedservername = Client.servernamecheck(nssrv) except ValueError as e: print("Invalid server name was provided. Please check server name and try again.") sys.exit(2) # Main Program try: while True: snmpload = subprocess.Popen(["snmpget", "-v", "2c", "-O", "qv", "-c", "public", "10.107.88.93", ".1.3.6.1.4.1.2021.10.1.3.1"], stdout=subprocess.PIPE) output, err = snmpload.communicate() value = re.sub(r'^"|"$', '', output) load = float(value) print(load) if load < 0.10: if x == 1: print("Load is normal..") time.sleep(5) else: print("Server enabled") Client.enablephysicalserver(normalizedservername) x = 1 y = 0 else: if y == 1: print("Server remains disabled..") time.sleep(5) else: Client.disablephysicalserver(normalizedservername) print("Server disabled") time.sleep(1) y = 1 x = 0 except KeyboardInterrupt: print("Script Killed by user") sys.exit(0)
- References
{{#widget:DISQUS
|id=networkm
|uniqid=Python Scripts
|url=https://aman.awiki.org/wiki/Python_Scripts
}}