-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSysOpsScript.py
More file actions
57 lines (51 loc) · 2.08 KB
/
Copy pathSysOpsScript.py
File metadata and controls
57 lines (51 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import subprocess,sys,re,socket,os,csv
# validition function to check ip addresess before changing keys#
def valid_ip4_addr(ip):
try:
socket.inet_aton(ip)
except socket.error:
return False
return True
#checks to see if key being sent through ssh-copy-id has correct permissions#
#required either 400 or 600, otherwise this script will not work without requring a password#
def valid_permission(authorized_key,keyPath):
args = ["stat","-c '%a'", keyPath]
permission = subprocess.check_output(args)
return '400' in permission or '600' in permission
#initialize vars#
key = "authorized_key_exercise.pub"
keyPathLocal = os.path.abspath(key)
outputArr = []
#commands to be executed on server#
hostCommand = "hostname"
ipCommand = "hostname -I"
mtimeCommand = "ls -l ~/.ssh/authorized_keys"
atimeCommand = "ls -lu ~/.ssh/authorized_keys"
ctimeCommand = "ls -lc ~/.ssh/authorized_keys"
updatedKeyCommand = "cat ~/.ssh/authorized_keys"
commandList = [hostCommand,ipCommand,mtimeCommand,ctimeCommand,atimeCommand,updatedKeyCommand]
command = " && ".join(commandList)
#main#
if not valid_permission(key,keyPathLocal):
print("Authorized key file does not have correct permissions (400) or (600)")
print("System exiting")
sys.exit()
for line in sys.stdin:
ip = re.sub('/s+','',line.strip('\n\r'))
if not valid_ip4_addr(ip):
print("ip is not in valid ip4 format \n" + ip)
# continue
# would skip over unvalid_ip4 addresses but I need my ipv6 for test purposes
scpCommand = "ssh-copy-id -i " + keyPathLocal + " " + ip
os.system(scpCommand)
args = ['ssh','-T',ip] # -T option prevents a pseudo-terminal allocation
# that interrupts with stdin in subprocess
process = subprocess.Popen(args,stdin=subprocess.PIPE,
stdout=subprocess.PIPE) #forks a new process
#given new file discriptors stdin,stdout
output = process.communicate(input= command)[0] #closes stdin
outputArr.append(re.sub('\n','\n,',output.lstrip('\n').rstrip('\n')))
process.wait() #waits for child process to end
with open("outputTestFile.csv", "wb") as myfile:
wr = csv.writer(myfile)
wr.writerow(outputArr)