Python Scripts: Difference between revisions

 
(31 intermediate revisions by the same user not shown)
Line 637:
== Save Netscaler config, Reboot & Verify ==
*Need to remove repeating code lines for connection from each function
 
<pre>
<syntaxhighlight lang="python">
import sys
import time
Line 645 ⟶ 646:
from nssrc.com.citrix.netscaler.nitro.resource.stat.system.system_stats import system_stats
 
class ns_edit :
ip = "10.107.88.78"
def __init__(self, ip, username, password):
username = "nsroot"
self.ip = ip
password = "pwd@123"
self.username = username
self.password = password
try:
self.client = nitro_service(self.ip,"http")
self.client.set_credential(self.username,self.password)
except nitro_exception as e:
print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
def uptime(self):
try:
node = system_stats.get(self.client)
for i in node:
print "Last reboot time is %s" %i.starttime
except nitro_exception as e:
print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
def reboot(self):
try:
self.client.reboot(True)
print "Node rebooted"
except nitro_exception as e:
print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
 
if __name__ == '__main__':
def uptime():
ns = ns_edit("10.107.88.78", "nsroot", "pwd@123")
client = nitro_service(ip,"http")
ns.uptime()
client.set_credential(username,password)
ns.reboot()
client.timeout = 20
time.sleep(60)
node = system_stats.get(client)
ns.uptime()
for i in node:
</syntaxhighlight>
print "Last reboot time is %s" %i.starttime
 
= Python Dice =
def save_cfg():
client = nitro_service(ip,"http")
client.set_credential(username,password)
client.timeout = 20
client.save_config()
print ("Config Saved")
 
<syntaxhighlight lang="python">
def reboot():
#!/usr/bin/env python3
client = nitro_service(ip,"http")
from tkinter import *
client.set_credential(username,password)
from random import randint
client.timeout = 20
import sys
client.reboot(True)
print ("Reboot Initiated")
 
root = Tk()
 
header = Label(root, text="Dice App v1.0", font=("Times", 35))
header.pack()
 
photo = PhotoImage(file="dice.gif")
 
label = Label(image=photo)
label.pack(side=RIGHT)
 
e = Entry(root, width=10, font=("Helvetica", 30, "bold"), justify=CENTER)
e.pack()
 
e.delete(0, END)
e.insert(0, "Ready!!")
 
def dice():
e.delete(0, END)
e.insert(0, randint(1,6))
 
def exit():
print("Bye Bye!!")
sys.exit()
 
a = Button(root, text="Roll Dice", width=20, command=dice)
a.pack()
 
f = Button(root, text="Exit App", width=20, fg="Red", command=exit)
f.pack()
 
root.geometry("400x200")
root.mainloop()
</syntaxhighlight>
 
 
= Weather Parcer =
*Need to register a account & get API Key from http://openweathermap.org
 
<syntaxhighlight lang="py>
import socket
import json
 
s = socket.socket()
addr = socket.getaddrinfo('api.openweathermap.org', 80)
 
s.connect(addr[0][4])
s.send(b'GET http://api.openweathermap.org/data/2.5/weather?q=Bangalore&appid=84d996853fcc4db149bc40acb09a3ef7_1 HTTP/1.0\r\n\r\n')
 
html = s.recv(1000)
div = html.split(b'\r\n\r\n')[-1]
data = json.loads(div)
 
main = data['weather'][0]['main']
print("Main =", main)
 
desc = data['weather'][0]['description']
print("Description =", desc)
 
Celcius = data['main']['temp'] - 273.15
rnd = str(round(Celcius,2))
print("Temperature =", rnd, "\xb0C")
 
pres = data['main']['pressure']
print("Pressure =", pres, "mbar")
 
hum = data['main']['humidity']
print("Humidity =", hum, "%")
 
vis = int(data['visibility'])/1000
print("Visibility =", vis, "Km?")
 
speed = data['wind']['speed']
try:
dir = data['wind']['deg']
uptime()
except KeyError:
save_cfg()
reboot() dir = 0
rnd2 = str(round(dir,2))
time.sleep(60)
print("Wind Speed =", speed, "Km/h?")
uptime()
print("Wind Direction =", rnd2, "Degree")
</syntaxhighlight>
 
= Plot Temperature using Thingspeak =
except nitro_exception as e:
*Need to register a account & get API Key from http://openweathermap.org
print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
*Need to register a account & get API Key from http://thingspeak.com
</pre>
 
== Upload Temperature ==
= Extensions Doctor =
Source: [https://askubuntu.com/questions/631900/correct-file-extensions askubuntu.com]
 
<syntaxhighlight lang="py>
<pre>
import socket
#!/usr/bin/env python3
import osjson
from time import strftime,localtime,sleep
import imghdr
 
import shutil
while True:
import sys
# Fetch Temperature from openweathermap.org
s = socket.socket()
addr = socket.getaddrinfo('api.openweathermap.org', 80)
 
s.connect(addr[0][4])
s.send(b'GET http://api.openweathermap.org/data/2.5/weather?q=Bangalore&appid=84d996853fcc4db149bc40acb09a3ef7_1 HTTP/1.0\r\n\r\n')
 
html = s.recv(1000)
div = html.split(b'\r\n\r\n')[-1]
data = json.loads(div.decode('utf-8'))
 
cel = data['main']['temp'] - 273.15
temp = float(round(cel,2))
 
# Upload Temperature Data to thingspeak.com
s2 = socket.socket()
addr2 = socket.getaddrinfo('api.thingspeak.com', 80)
 
s2.connect(addr2[0][4])
s2.send(b'POST https://api.thingspeak.com/update?api_key=XB15HC17CZH6KYMV_1&field1=%f HTTP/1.0\r\n\r\n' % temp)
html2 = s2.recv(1000)
div2 = html2.split(b' ')[1]
 
# Check if logged data successfully
if int(div2) == 200:
currtime = strftime("%H:%M:%S %d-%b-%Y", localtime())
print("Uploaded Data @", currtime,":", "Temp =", temp, "\xb0C")
else:
print("HTTP Error:", int(div2))
 
# Wait for 10 minutes
directory = sys.argv[1]
sleep(600)
</syntaxhighlight>
 
== Bulk Upload Parameters ==
 
<syntaxhighlight lang="python">
# Need to add a section for no extensions
import socket
# Need to write Results to a file in script dir
import json
from time import strftime,localtime,sleep
import requests
 
# Fetch Temperature from openweathermap.org
for root, dirs, files in os.walk(directory):
def weather():
for name in files:
files = root+"/"+namesocket.socket()
addr = socket.getaddrinfo('api.openweathermap.org', 80)
s.connect(addr[0][4])
s.send(b'GET http://api.openweathermap.org/data/2.5/weather?q=Bangalore&units=metric&appid=84d996853fcc4db149bc40acb09a3ef7_1 HTTP/1.0\r\n\r\n')
html = s.recv(1000)
s.close()
div = html.split(b'\r\n\r\n')[-1]
data = json.loads(div.decode('utf-8'))
return data
 
def thing():
# find the correct extension
# Call weather function
ftype = imghdr.what(file)
data = weather()
temp = data['main']['temp']
pres = data['main']['pressure']
hum = data['main']['humidity']
vis = int(data['visibility'])/1000
speed = data['wind']['speed']
try:
dir = data['wind']['deg']
except KeyError:
dir = 0
ctime = strftime("%Y-%m-%d %H:%M:%S +0530", localtime())
print("Data Fetched @",ctime,":","Temp(C)=",temp,"\xb0C","Press(hPa)=",pres,"Hum(%)=",hum,"Vis(Km)=",vis,"Speed(m/s)=",speed,"Dir(deg)=",dir)
# Upload Temperature Data to thingspeak.com
payload = {"write_api_key":"G97NZS1XWXCS798C_1","updates":[{"created_at":ctime,"field1":temp,"field2":pres,"field3":hum,"field4":vis,"field5":speed,"field6":dir}]}
url = 'https://api.thingspeak.com/channels/396314/bulk_update.json'
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
return response
 
while True:
ext = os.path.splitext(file)[1][1:]
response = thing()
# find files with the (incorrect) extension to rename
if ftype != ext:
if ftype != None:
# rename the file
shutil.move(file, file.replace(ext,ftype))
print (file, ext, ("=>"), ftype)
 
# Check if logged data successfully
# in case it can't be determined, mention it in the output
if response.status_code == 202:
else:
print("couldData notsuccessfully uploaded determine:", "+fileresponse.status_code)
# else:
# print (name,"HTTP Error Code:"Correct, Extension"response.status_code)
 
# Wait for 10 minutes
# else:
sleep(600)
# print "Unknown file type"
</syntaxhighlight>
 
== Slack Webhook POST ==
<syntaxhighlight lang="python">
#!/usr/bin/python
import json
import requests
 
requests.packages.urllib3.disable_warnings()
for root, dirs, files in os.walk(directory):
for name in files:
file = root+"/"+name
 
# Create the webhook at https://my.slack.com/services/new/incoming-webhook/
# remove double extensions
webhook_url = 'https://hooks.slack.com/services/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'
fn1, ext = os.path.splitext(file)
slack_data = {'text': "Sev1 Incident: Pool is Down :skull:"}
fn2, ext2 = os.path.splitext(fn1)
if ext == ext2:
print (ext2)
# Merge similar extensions
shutil.move(file, fn1.replace(ext,ext2))
print (fn2, ext, ("Dup ext removed:"), ext2)
else:
print (file, " has 1 extension")
 
response = requests.post(
</pre>
webhook_url, data=json.dumps(slack_data),
headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
raise ValueError(
'Request to slack returned an error %s, the response is:\n%s'
% (response.status_code, response.text)
)
</syntaxhighlight>