Created
February 1, 2024 19:54
-
-
Save azazar/7ded966bc36a07bfc6ebf9ef3196caee to your computer and use it in GitHub Desktop.
Start/stop SSHD in Termux when power and wifi are connected
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/data/data/com.termux/files/usr/bin/python3 | |
import json | |
import os | |
import subprocess | |
import time | |
import logging | |
import signal | |
# Configuration | |
DESIRED_BSSID = "02:00:00:00:00:00" | |
CHECK_INTERVAL = 60 # in seconds | |
# Set up logging | |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
sshd_process = None # Global variable for the SSHD subprocess | |
def run_command(command): | |
"""Execute a command and return JSON output.""" | |
try: | |
return json.loads(os.popen(command).read()) | |
except Exception as e: | |
logging.error(f"Error executing command '{command}': {e}") | |
return None | |
def check_conditions(): | |
"""Check if the device is charging and connected to the desired BSSID.""" | |
status = run_command('termux-battery-status') | |
wifi_info = run_command('termux-wifi-connectioninfo') | |
return (status and status['plugged'] != 'UNPLUGGED') and \ | |
(wifi_info and wifi_info['bssid'] == DESIRED_BSSID) | |
def start_sshd(): | |
"""Start the SSHD service.""" | |
global sshd_process | |
if sshd_process is None: | |
logging.info("Starting sshd...") | |
os.system('termux-wake-lock') | |
sshd_process = subprocess.Popen(['sshd', '-D']) | |
def stop_sshd(): | |
"""Stop the SSHD service.""" | |
global sshd_process | |
if sshd_process: | |
logging.info("Stopping sshd...") | |
sshd_process.terminate() | |
sshd_process.wait() | |
sshd_process = None | |
os.system('termux-wake-unlock') | |
def cleanup(signum, frame): | |
"""Cleanup resources on script termination.""" | |
logging.info("Cleanup initiated...") | |
stop_sshd() | |
exit(0) | |
def main(): | |
signal.signal(signal.SIGINT, cleanup) | |
signal.signal(signal.SIGTERM, cleanup) | |
while True: | |
if check_conditions(): | |
start_sshd() | |
else: | |
stop_sshd() | |
time.sleep(CHECK_INTERVAL) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment