-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
executable file
·175 lines (141 loc) · 5.48 KB
/
main.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#!/usr/bin/env python3
import subprocess
import getpass
import time
import pdb
import configparser
import sys
import logging
import requests
def parse_config(path):
config = configparser.ConfigParser()
try:
config.read(path)
emitter = config['emitters']['emitter']
if emitter == '':
logging.critical("Missing emitter type.")
sys.exit()
elif str.lower(emitter) != 'email' and str.lower(emitter) != 'telegram':
logging.critical("Emitter type must be either email or telegram.")
sys.exit()
except KeyError:
logging.critical("Please check /etc/zypper-automatic.conf")
sys.exit()
return config
def check_root():
if getpass.getuser() != "root":
logging.critical("Must be root to execute zypper commands.")
sys.exit()
def refresh_repos():
for i in range(0, 2):
try:
logging.info("Refreshing repositories...")
output = subprocess.check_output(["zypper", "refresh"])
except CalledProcessError:
time.sleep(300)
continue
break
else:
logging.warning("An error occured while refreshing repos. See output below.")
print(err.output)
output = err.output
return output
def list_patches():
try:
logging.info("Retrieving list of all patches...")
output = subprocess.check_output(["zypper", "list-patches"])
except subprocess.CalledProcessError as err:
logging.warning("An error occured while listing patches. See output below.")
print(err.output)
output = err.output
return output
def install_patches(categories, with_interactive):
command = ["zypper", "patch", "--no-confirm", "--details"]
if categories != '':
categories_list = categories.replace(" ", "").split(',')
for c in categories_list:
if "--category" not in command:
command.append("--category")
if str.lower(c) == "security":
command.append("security")
if str.lower(c) == "recommended":
command.append("recommended")
if str.lower(c) == "optional":
command.append("optional")
if str.lower(c) == "feature":
command.append("feature")
if str.lower(c) == "document":
command.append("document")
if str.lower(c) == "yast":
command.append("yast")
else:
logging.warning("No categories specified. All patches will be installed.")
if str.lower(with_interactive) == "true":
command.append("--with-interactive")
try:
logging.info("Installing patches...")
output = subprocess.check_output(command)
except subprocess.CalledProcessError as err:
if err.returncode == 102:
logging.info("Reboot required.")
output = err.output
else:
logging.warning("An error occured while installing patches. See output below.")
print(err.output)
return output
def send_email(content, subject, email_to):
message = subprocess.Popen(["echo", content], stdout=subprocess.PIPE)
command = subprocess.Popen(["mail", "-s", subject, email_to],
stdin=message.stdout,
stdout=subprocess.PIPE)
message.stdout.close()
logging.info("Sending email...")
output = command.communicate()[0]
return output
def send_telegram(content, token, chat_id):
url = f'https://api.telegram.org/bot{token}/sendMessage?text={content}&chat_id={chat_id}'
logging.info("Sending Telegram message...")
r = requests.get(url)
return r
def compose_body(time_start, refresh_output, install_output, list_output):
if install_output == None:
outputs = {'refresh_output': refresh_output,
'list_output': list_output}
else:
outputs = {'refresh_output': refresh_output,
'install_output': install_output,
'list_output': list_output}
# Convert bytes to strings if needed.
for key, value in outputs.items():
if type(value) is bytes:
outputs[key] = str(value, 'utf-8')
head = f"JOB STARTED: {time_start}"
# Combine outputs to create body of message.
body = "\n".join(outputs.values())
return body
if __name__ == "__main__":
logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging.INFO)
# Root is required in order to run zypper
check_root()
config = parse_config('/etc/zypper-automatic.conf')
categories = config['zypper']['patch_categories']
with_interactive = config['zypper']['with_interactive']
list_only = config['zypper']['list_only']
emitter = config['emitters']['emitter']
email_to = config['email']['email_to']
token = config['telegram']['token']
chat_id = config['telegram']['chat_id']
time_start = time.asctime(time.localtime(time.time()))
refresh_output = refresh_repos()
if str.lower(list_only) != "true":
install_output = install_patches(categories, with_interactive)
else:
install_output = None
list_output = list_patches()
body = compose_body(time_start, refresh_output, install_output, list_output)
# For emails only
subject = "zypper-automatic"
if str.lower(emitter) == 'email':
send_email(body, subject, email_to)
elif str.lower(emitter) == 'telegram':
send_telegram(body, token, chat_id)