diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9c3e7fb --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.*journal +.*lastused diff --git a/mutex_access.sh b/mutex_access.sh new file mode 100755 index 0000000..342dc3c --- /dev/null +++ b/mutex_access.sh @@ -0,0 +1,95 @@ +#!/bin/bash +set -e + +port=22 # default SSH port +cache=".maccess-lastused" +journal=".maccess-journal" +user_host="" +user="default" +jump="" +lock_file="lock.mutex" + +usage() { + echo "Usage: $0 [-p PORT -J jump1,jump2] user@host" + exit 1 +} + +# Parse command line options +while getopts ":p:J:u:" opt; do + case $opt in + p) + if ! [[ "$OPTARG" =~ ^[0-9]+$ ]] || [ "$OPTARG" -gt 65535 ]; then + echo "Invalid port number: $OPTARG" + exit 1 + fi + port="$OPTARG" + ;; + J) + jump="-J $OPTARG" + echo "ProxyJump: $jump" + ;; + u) + user="$OPTARG" + ;; + \?) + echo "Invalid option: -$OPTARG" + usage + ;; + :) + echo "Option -$OPTARG requires an argument" + exit 1 + ;; + esac +done +shift $((OPTIND -1)) + +if [ $# -ne 1 ]; then + echo "Using $cache" + + if [ -f "$cache" ]; then + { + read -r jump_cached + read -r port_cached + read -r user_host_cached + } < "$cache" + jump="$jump_cached" + port="$port_cached" + user_host="$user_host_cached" + else + echo "Error: Cache file $cache not found." >&2 + usage + fi +else + user_host="$1" + echo "$jump" > "$cache" + echo "$port" >> "$cache" + echo "$user_host" >> "$cache" +fi + + +# Check if lock file exists on remote +if ssh $jump -p "$port" "$user_host" "test -e '$lock_file'"; then + echo "Error: Lock file $lock_file exists on $user_host" >&2 + whoisusing=$(ssh $jump -p $port $user_host "cat $lock_file") + echo "At the moment in use by $whoisusing" >&2 + echo "Session might be active. Exiting." >&2 + exit 1 +fi + +# Create lock file +ssh $jump -p "$port" "$user_host" "echo '$user' > '$lock_file'" +echo "Locked for user $user" +echo "[Start] [$(date +%Y-%m-%d-%H-%M-%S)] $user" >> $journal +cleanup() { + echo "Removing lock file..." + ssh $jump -p "$port" "$user_host" "rm -f '$lock_file'" + echo "[End] [$(date +%Y-%m-%d-%H-%M-%S)] $user" >> $journal +} + +# Register cleanup trap +trap cleanup EXIT INT TERM + +# Start interactive session +echo "Starting SSH session (port $port). Lock file created." +ssh $jump -p "$port" "$user_host" +