mirror of
https://codeberg.org/privacy1st/exec-notify
synced 2024-12-22 23:16:04 +01:00
first commit
This commit is contained in:
commit
f323b691db
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
config/cfg.ini
|
||||
__pycache__/
|
0
.idea/.gitignore
generated
vendored
Normal file
0
.idea/.gitignore
generated
vendored
Normal file
8
.idea/execNotify.iml
generated
Normal file
8
.idea/execNotify.iml
generated
Normal file
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="jdk" jdkName="Python 3.7 (venv37)" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
14
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
14
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
@ -0,0 +1,14 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<option name="ignoredErrors">
|
||||
<list>
|
||||
<option value="N802" />
|
||||
<option value="N803" />
|
||||
<option value="N806" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
6
.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
6
.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
4
.idea/misc.xml
generated
Normal file
4
.idea/misc.xml
generated
Normal file
@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (venv37)" project-jdk-type="Python SDK" />
|
||||
</project>
|
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/execNotify.iml" filepath="$PROJECT_DIR$/.idea/execNotify.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
122
.idea/workspace.xml
generated
Normal file
122
.idea/workspace.xml
generated
Normal file
@ -0,0 +1,122 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="066dfbfd-85ed-456f-9525-253ec03fa96b" name="Default Changelist" comment="">
|
||||
<change afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/.idea/.gitignore" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/.idea/execNotify.iml" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/.idea/inspectionProfiles/Project_Default.xml" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/.idea/inspectionProfiles/profiles_settings.xml" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/.idea/modules.xml" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/config.py" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/config/cfg.ini.example" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/exec.py" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/execNotify.py" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/mail.py" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/password.txt" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/util.py" afterDir="false" />
|
||||
</list>
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||
</component>
|
||||
<component name="FileTemplateManagerImpl">
|
||||
<option name="RECENT_TEMPLATES">
|
||||
<list>
|
||||
<option value="Python Script" />
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="Git.Settings">
|
||||
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
|
||||
</component>
|
||||
<component name="ProjectId" id="1lHIVbTIy9t8txmMM3V80GDBa2N" />
|
||||
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
|
||||
<component name="ProjectViewState">
|
||||
<option name="hideEmptyMiddlePackages" value="true" />
|
||||
<option name="showLibraryContents" value="true" />
|
||||
</component>
|
||||
<component name="PropertiesComponent">
|
||||
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
|
||||
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
|
||||
<property name="WebServerToolWindowFactoryState" value="false" />
|
||||
<property name="last_opened_file_path" value="$PROJECT_DIR$/config" />
|
||||
<property name="node.js.detected.package.eslint" value="true" />
|
||||
<property name="node.js.detected.package.tslint" value="true" />
|
||||
<property name="node.js.path.for.package.eslint" value="project" />
|
||||
<property name="node.js.path.for.package.tslint" value="project" />
|
||||
<property name="node.js.selected.package.eslint" value="(autodetect)" />
|
||||
<property name="node.js.selected.package.tslint" value="(autodetect)" />
|
||||
</component>
|
||||
<component name="RecentsManager">
|
||||
<key name="CopyFile.RECENT_KEYS">
|
||||
<recent name="$PROJECT_DIR$/config" />
|
||||
<recent name="$PROJECT_DIR$" />
|
||||
</key>
|
||||
</component>
|
||||
<component name="RunManager">
|
||||
<configuration name="execNotify" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
|
||||
<module name="execNotify" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="PARENT_ENVS" value="true" />
|
||||
<envs>
|
||||
<env name="PYTHONUNBUFFERED" value="1" />
|
||||
</envs>
|
||||
<option name="SDK_HOME" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||
<option name="IS_MODULE_SDK" value="true" />
|
||||
<option name="ADD_CONTENT_ROOTS" value="true" />
|
||||
<option name="ADD_SOURCE_ROOTS" value="true" />
|
||||
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
|
||||
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/execNotify.py" />
|
||||
<option name="PARAMETERS" value="ls foobar" />
|
||||
<option name="SHOW_COMMAND_LINE" value="false" />
|
||||
<option name="EMULATE_TERMINAL" value="false" />
|
||||
<option name="MODULE_MODE" value="false" />
|
||||
<option name="REDIRECT_INPUT" value="false" />
|
||||
<option name="INPUT_FILE" value="" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<recent_temporary>
|
||||
<list>
|
||||
<item itemvalue="Python.execNotify" />
|
||||
</list>
|
||||
</recent_temporary>
|
||||
</component>
|
||||
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
|
||||
<component name="TaskManager">
|
||||
<task active="true" id="Default" summary="Default task">
|
||||
<changelist id="066dfbfd-85ed-456f-9525-253ec03fa96b" name="Default Changelist" comment="" />
|
||||
<created>1607247615238</created>
|
||||
<option name="number" value="Default" />
|
||||
<option name="presentableId" value="Default" />
|
||||
<updated>1607247615238</updated>
|
||||
<workItem from="1607247616426" duration="265000" />
|
||||
<workItem from="1607248714632" duration="2640000" />
|
||||
<workItem from="1607251381674" duration="2626000" />
|
||||
<workItem from="1607254060327" duration="231000" />
|
||||
<workItem from="1607254312912" duration="2639000" />
|
||||
</task>
|
||||
<servers />
|
||||
</component>
|
||||
<component name="TypeScriptGeneratedFilesManager">
|
||||
<option name="version" value="3" />
|
||||
</component>
|
||||
<component name="Vcs.Log.Tabs.Properties">
|
||||
<option name="TAB_STATES">
|
||||
<map>
|
||||
<entry key="MAIN">
|
||||
<value>
|
||||
<State />
|
||||
</value>
|
||||
</entry>
|
||||
</map>
|
||||
</option>
|
||||
</component>
|
||||
<component name="com.intellij.coverage.CoverageDataManagerImpl">
|
||||
<SUITE FILE_PATH="coverage/execNotify$execNotify.coverage" NAME="execNotify Coverage Results" MODIFIED="1607256518765" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
|
||||
</component>
|
||||
</project>
|
34
config.py
Normal file
34
config.py
Normal file
@ -0,0 +1,34 @@
|
||||
from pathlib import Path
|
||||
import configparser
|
||||
|
||||
|
||||
def getHostAndPort():
|
||||
return config['mail']['host'], config['mail']['port']
|
||||
|
||||
|
||||
def getPassword():
|
||||
return config['mail']['password']
|
||||
|
||||
|
||||
def getFrom():
|
||||
return config['mail']['from'] # used for mail login as well
|
||||
|
||||
|
||||
def getTo():
|
||||
return config['mail']['to']
|
||||
|
||||
|
||||
def getErrorFile() -> Path:
|
||||
return Path(config['file']['errorfile'])
|
||||
|
||||
|
||||
def _getCfgFile() -> Path:
|
||||
return _getCfgDir().joinpath('cfg.ini')
|
||||
|
||||
|
||||
def _getCfgDir() -> Path:
|
||||
return Path('config')
|
||||
|
||||
|
||||
config: configparser.ConfigParser = configparser.ConfigParser()
|
||||
config.read(_getCfgFile())
|
12
config/cfg.ini.example
Normal file
12
config/cfg.ini.example
Normal file
@ -0,0 +1,12 @@
|
||||
[DEFAULT]
|
||||
|
||||
[mail]
|
||||
host = smtp.example.com
|
||||
port = 465
|
||||
password = examplePassword
|
||||
|
||||
from = noreply@example.com
|
||||
to = me@example.com
|
||||
|
||||
[file]
|
||||
errorfile = /home/exampleUser/ERROR.mail
|
22
exec.py
Normal file
22
exec.py
Normal file
@ -0,0 +1,22 @@
|
||||
from typing import List
|
||||
import sys
|
||||
import subprocess
|
||||
|
||||
|
||||
def execute(command: List[str]):
|
||||
"""
|
||||
Run the given command in a subprocess and pass stdin (if given) to that process.
|
||||
Wait for command to complete.
|
||||
|
||||
:param command: A command to executed as list of words, e.g. ["echo", "hello"]
|
||||
:return: (status, stdout, stderr)
|
||||
"""
|
||||
|
||||
completed: subprocess.CompletedProcess = subprocess.run(
|
||||
command,
|
||||
stdin=sys.stdin,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
text=True
|
||||
)
|
||||
return completed.returncode, completed.stdout, completed.stderr
|
59
execNotify.py
Executable file
59
execNotify.py
Executable file
@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
from sys import argv
|
||||
import socket
|
||||
|
||||
import exec, mail, config
|
||||
|
||||
|
||||
def main():
|
||||
prevMailError = checkPrevError()
|
||||
success = executeCommand()
|
||||
if prevMailError:
|
||||
tryToInform()
|
||||
|
||||
if not prevMailError or not success:
|
||||
exit(1)
|
||||
else:
|
||||
exit(0)
|
||||
|
||||
|
||||
def executeCommand() -> bool:
|
||||
if len(argv) < 2:
|
||||
return True
|
||||
else:
|
||||
keys = ['command', 'status', 'stderr', 'stdout']
|
||||
code, stdout, stderr = exec.execute(argv[1:])
|
||||
values = [str(argv[1:]), str(code), stderr, stdout]
|
||||
|
||||
BODY = ''
|
||||
for key, value in zip(keys, values):
|
||||
BODY += '=== {} ===\n{}\n'.format(key, value)
|
||||
print(BODY)
|
||||
|
||||
if code != 0:
|
||||
hostname = socket.gethostname()
|
||||
|
||||
SUBJECT = '{} | {}'.format(hostname, str(argv[1:]))
|
||||
mail.sendMailOrWriteToFile(SUBJECT=SUBJECT, BODY=BODY)
|
||||
return False
|
||||
|
||||
|
||||
def checkPrevError():
|
||||
return config.getErrorFile().exists()
|
||||
|
||||
|
||||
def tryToInform():
|
||||
"""
|
||||
Try to inform user via mail about previous error(s) that could not be sent to him before.
|
||||
Maybe this time sending of an email works ;)
|
||||
"""
|
||||
|
||||
SUBJECT = '{} | Some mails not sent!'.format(socket.gethostname())
|
||||
BODY = 'Please check the file {} for mails which could previously not be sent to you!\n' \
|
||||
'Note: You may delete the file after reading it ;)'.format(
|
||||
config.getErrorFile())
|
||||
mail.sendMail(SUBJECT=SUBJECT, BODY=BODY)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
69
mail.py
Normal file
69
mail.py
Normal file
@ -0,0 +1,69 @@
|
||||
import sys
|
||||
import datetime
|
||||
import smtplib, ssl
|
||||
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from pathlib import Path
|
||||
|
||||
import util, config
|
||||
|
||||
|
||||
def sendMailOrWriteToFile(SUBJECT: str, BODY: str):
|
||||
try:
|
||||
sendMail(SUBJECT=SUBJECT, BODY=BODY)
|
||||
except Exception as e:
|
||||
print("Error: Could not send mail! Writing to file instead ...", file=sys.stderr)
|
||||
print(e, file=sys.stderr)
|
||||
|
||||
# Instead, try to save the mail so that the user can read
|
||||
# it later when connected to this computer
|
||||
saveMail(SUBJECT=SUBJECT, BODY=BODY)
|
||||
|
||||
|
||||
def sendMail(SUBJECT: str, BODY: str):
|
||||
"""
|
||||
:throws Exception: if mail could not be sent
|
||||
"""
|
||||
|
||||
FROM = config.getFrom()
|
||||
TO = config.getTo()
|
||||
password = config.getPassword()
|
||||
|
||||
# Create a secure SSL context
|
||||
context = ssl.create_default_context()
|
||||
|
||||
host, port = config.getHostAndPort()
|
||||
with smtplib.SMTP_SSL(host=host, port=port, context=context) as server:
|
||||
server.login(FROM, password)
|
||||
message = MIMEMultipart()
|
||||
message["Subject"] = SUBJECT
|
||||
message["From"] = FROM
|
||||
message["To"] = TO
|
||||
message["Bcc"] = TO # Recommended for mass emails
|
||||
# Turn plain/html message_body into plain/html MIMEText objects
|
||||
message.attach(MIMEText(BODY, "plain"))
|
||||
|
||||
server.sendmail(FROM, TO, message.as_string())
|
||||
|
||||
|
||||
def saveMail(SUBJECT: str, BODY: str):
|
||||
"""
|
||||
This method does NOT throw exceptions
|
||||
"""
|
||||
|
||||
time = datetime.datetime.now()
|
||||
timeStr = time.strftime('%Y%m%d_%H%M%S')
|
||||
|
||||
DATE = '=' * 20 + '\n=== date ===\n' + timeStr + '\n'
|
||||
SUBJECT = '=== subject ===\n' + SUBJECT + '\n'
|
||||
|
||||
try:
|
||||
# append to file; create file if not existent
|
||||
with open(config.getErrorFile(), "a") as f:
|
||||
f.write(DATE)
|
||||
f.write(SUBJECT)
|
||||
f.write(BODY)
|
||||
except Exception as e:
|
||||
print('Error: Could not write to file!', file=sys.stderr)
|
||||
print(e, file=sys.stderr)
|
1
password.txt
Normal file
1
password.txt
Normal file
@ -0,0 +1 @@
|
||||
odf48p7k3
|
Loading…
Reference in New Issue
Block a user