Skip to content

Commit aaf70b3

Browse files
author
Anurag Guda
committed
Python Scripting
1 parent 2062e01 commit aaf70b3

File tree

6 files changed

+243
-1
lines changed

6 files changed

+243
-1
lines changed

README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,7 @@
1-
# Python-Scripting
1+
# Python-Scripting
2+
3+
This respository helps you to understand basic python scripting for automation.
4+
5+
Please find some of my scripts, will add more scripts depends on general usage
6+
7+

fibonacci.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#! /Users/aguda/opt/anaconda3/bin/python3
2+
3+
r = int(input("Please enter a number to list fibanacci Series: "))
4+
5+
def fibanacci(n):
6+
n1,n2 = 0,1
7+
count = 0
8+
if n <= 0:
9+
print("Please enter number at least 1:")
10+
elif n == 1:
11+
return 0
12+
else:
13+
while count <= n:
14+
print(n1)
15+
n1,n2 = n2, n1+n2
16+
count += 1
17+
18+
print(fibanacci(r))
19+
20+
21+
'''
22+
# Number of fibonacci number for give value
23+
def fibanacci(n):
24+
if n<0:
25+
print("Please enter number at least 1:")
26+
elif n == 1:
27+
return 0
28+
elif n == 2:
29+
return 1
30+
else:
31+
return fibanacci(n-1)+fibanacci(n-2)
32+
'''

ipinfo.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
2+
"""
3+
This Program help you to find origin country of a website
4+
and also provides you detail information of whois
5+
"""
6+
7+
import socket
8+
import requests
9+
import os
10+
11+
host = input("Please Enter a website to find it's origin: ")
12+
addra = socket.gethostbyname(host)
13+
url = 'http://ipinfo.io/{}'.format(addra)
14+
country = requests.get(url, verify=False)
15+
print("{} hosted country is: ".format(host) + country.json()['country'])
16+
print('#' * 50)
17+
print("{} whois information".format(host))
18+
print('*' * 50)
19+
sys = os.system('whois {}'.format(addra))

redfish.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#! /Users/aguda/opt/anaconda3/bin/python3
2+
3+
import sys,os,json,requests
4+
from requests.packages.urllib3.exceptions import InsecureRequestWarning
5+
6+
# Function to get UUID and Serial Number of a Server
7+
def res(url,user,passw):
8+
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
9+
a = requests.get(url,verify=False,auth=(user, passw))
10+
return '{} Server UUID is: '.format(host) + a.json()['UUID']+"\n"+'{} Server Serial Number is: '.format(host) + a.json()['SerialNumber']
11+
12+
# Input file with read line by line
13+
file = sys.argv[1]
14+
f = open(file,'r')
15+
lines = f.readlines()
16+
17+
# Itterate the each host to get the RedFish Details
18+
for item in lines:
19+
# Split based on ":" from file
20+
ip = item.strip().split(':')
21+
host = ip[0]
22+
print('\n' + '*' * 70)
23+
# method to validate whether the server is valid for RedFish API
24+
try:
25+
url = "https://{}/redfish/v1/".format(host)
26+
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
27+
response = requests.get(url, verify=False,timeout=3)
28+
# method to get valid RedFish Server details with help of res function
29+
try:
30+
oe = response.json()['Oem']
31+
#Itterate the OEM Patners to get the server details
32+
for item in oe:
33+
if item == 'Dell':
34+
dellurl = "https://{}/redfish/v1/Systems/System.Embedded.1".format(host)
35+
print("{} Server Service Tag is: ".format(host) + oe['Dell']['ServiceTag'])
36+
print(res(dellurl,ip[1],ip[2]))
37+
elif item == 'Ami':
38+
amiurl = "https://{}/redfish/v1/Systems/Self".format(host)
39+
print(res(amiurl,ip[1],ip[2]))
40+
elif item == 'Hp':
41+
hpurl = "https://{}/redfish/v1/Systems/1/".format(host)
42+
print(res(hpurl,ip[1],ip[2]))
43+
else:
44+
smurl = "https://{}/redfish/v1/Systems/1".format(host)
45+
print(res(hpurl,ip[1],ip[2]))
46+
except Exception as e:
47+
if 'Oem' in str(e):
48+
atosurl = "https://{}/redfish/v1".format(host)
49+
atos = requests.get(atosurl,verify=False)
50+
print('Atos Server {} UUI is: '.format(host) + atos.json()['UUID'])
51+
except:
52+
print('{} Server is not for RedFish API'.format(host))

sendmail.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import smtplib
2+
import getpass
3+
from email.mime.text import MIMEText
4+
from email.mime.multipart import MIMEMultipart
5+
import datetime
6+
import re
7+
8+
def mail():
9+
"""
10+
Docstring for mail function
11+
mail(receiver), receiver should be email address
12+
this function will ask sender email and password
13+
for GMAIL, please make sure to allow less secure apps
14+
https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none
15+
"""
16+
split_term = '@'
17+
sender = str(input("Please enter sender email: "))
18+
receiver = str(input("Please enter receiver email: "))
19+
sen = re.split(split_term, sender)
20+
if sen[1] == 'gmail.com':
21+
allow = str(input("Did you enable allow secure apps on gmail settings y or n? "))
22+
if allow.lower() == 'y':
23+
password = getpass.getpass(prompt='Enter {} Password password: '.format(sender))
24+
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
25+
smtpObj.starttls()
26+
smtpObj.login(sender, password)
27+
message = MIMEMultipart()
28+
message["Subject"] = "Email generated by Python"
29+
message["From"] = sender
30+
message["To"] = receiver
31+
user = re.split(split_term, receiver)
32+
# Write the mail body text part
33+
text = """Hi, {} \nThis email generated by Python programm! \nEmail generated on """.format(user[0]) +str(datetime.datetime.now().strftime("%Y %m %d %H:%M:%S'"))
34+
part1 = MIMEText(text, "plain")
35+
message.attach(part1)
36+
try:
37+
smtpObj.sendmail(sender, receiver, message.as_string())
38+
print("{} Sent an email to {}".format(message.as_string(), receiver))
39+
except:
40+
print('error sending mail to {}'.format(receiver))
41+
smtpObj.quit()
42+
else:
43+
print("Please enable allow secure apps on https://myaccount.google.com/u/0/lesssecureapps?pli=1&pageId=non")
44+
else:
45+
print("sender email {} is different than gmail.com".format(sen[1]))
46+
47+
mail(receiver)

ssh.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#! /Users/aguda/opt/anaconda3/bin/python3
2+
3+
import getpass
4+
import sys
5+
import time
6+
import paramiko
7+
from scp import SCPClient
8+
9+
10+
class Ssh:
11+
"""
12+
docstring for Ssh Class
13+
Ssh(hostname, user, password)
14+
hostname should host IP
15+
user should be username of host
16+
password should password of host
17+
"""
18+
def __init__(self, host, user, password):
19+
self.host = host
20+
self.user = user
21+
self.password = password
22+
23+
def ssh(self, command):
24+
"""
25+
docstring for ssh function
26+
ssh(command)
27+
command should input for this function to get the results of remote host
28+
"""
29+
ssh = paramiko.SSHClient()
30+
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
31+
ssh.connect(self.host, port="22", username=self.user, password=self.password, timeout='5')
32+
(stdin, stdout, stderr) = ssh.exec_command(command)
33+
stdin.write(password + '\n')
34+
stdin.flush()
35+
#print(stdout.readlines())
36+
print("".join(stdout.readlines()))
37+
ssh.close()
38+
39+
class Scp(Ssh):
40+
"""
41+
docstring for SCP Class
42+
SCP(hostname, user, password)
43+
inherited from source Ssh class
44+
hostname should host IP
45+
user should be username of host
46+
password should password of host
47+
"""
48+
def scp(self, file):
49+
"""
50+
docstring for scp function
51+
scp(file)
52+
file should input for this function to copy the file to remote host
53+
"""
54+
ssh = paramiko.SSHClient()
55+
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
56+
ssh.connect(self.host, port="22", username=self.user, password=self.password, timeout='5')
57+
scp = SCPClient(ssh.get_transport())
58+
print("Copy {} from local to {}".format(file, self.host))
59+
scp.put(file, recursive=True, remote_path='/tmp/')
60+
# copy from remote host to local
61+
# scp.get(file)
62+
ssh.close()
63+
64+
65+
66+
if __name__ == '__main__':
67+
user = "nvidia"
68+
if len(sys.argv) < 3:
69+
print("Please pass arguments to scirpt as 'python ssh.py hostip command filename'")
70+
sys.exit()
71+
elif len(sys.argv) == 3:
72+
password = getpass.getpass(prompt='Enter password: ')
73+
hostname = sys.argv[1]
74+
cmd = sys.argv[2]
75+
HOST = Ssh(hostname, user, password)
76+
HOST.ssh(cmd)
77+
elif len(sys.argv) == 4:
78+
password = getpass.getpass(prompt='Enter password: ')
79+
hostname = sys.argv[1]
80+
cmd = sys.argv[2]
81+
file = sys.argv[3]
82+
HOSTONE = Scp(hostname, user, password)
83+
HOSTONE.scp(file)
84+
time.sleep(10)
85+
HOST = Ssh(hostname, user, password)
86+
HOST.ssh(cmd)

0 commit comments

Comments
 (0)