Skip to content

Instantly share code, notes, and snippets.

@theSoberSobber
Last active November 19, 2024 07:52
Show Gist options
  • Save theSoberSobber/844a4263a3ebc5cf8960ae12384aab90 to your computer and use it in GitHub Desktop.
Save theSoberSobber/844a4263a3ebc5cf8960ae12384aab90 to your computer and use it in GitHub Desktop.
current ip of my home server, with a max lag of 60 seconds
{"ip": "116.72.194.187"}
@theSoberSobber
Copy link
Author

x11vnc for display 0 using xfce.

@theSoberSobber
Copy link
Author

import os
import requests
from datetime import datetime

# Global variables
GIST_ID = "844a4263a3ebc5cf8960ae12384aab90"
FILENAME = "server.json"  # Set the filename here
IP_FILE = "/home/meso/Desktop/monitor/ip.txt"
TOKEN_FILE = "/home/meso/Desktop/monitor/pat"

def read_token_from_file(filename):
    """
    Read the Personal Access Token (PAT) from a file.

    Parameters:
    - filename (str): Name of the file containing the PAT.

    Returns:
    - str: The PAT read from the file.
    """
    with open(filename, "r") as file:
        token = file.read().strip()
    return token

def read_ip_from_file(filename):
    """
    Read the IP address from a file.

    Parameters:
    - filename (str): Name of the file containing the IP address.

    Returns:
    - str: The IP address read from the file, or None if the file does not exist or is empty.
    """
    if os.path.exists(filename):
        with open(filename, "r") as file:
            ip = file.read().strip()
            if ip:
                return ip
    return None

def get_current_ip():
    """
    Fetch the current public IP address from https://checkip.amazonaws.com/.

    Returns:
    - str: The current public IP address, or None if unable to fetch.
    """
    try:
        response = requests.get("https://checkip.amazonaws.com/")
        return response.text.strip()
    except requests.RequestException as e:
        print(f"Failed to fetch current IP address: {e}")
        return None

def update_gist(new_ip):
    """
    Update the Gist with the new IP address.

    Parameters:
    - new_ip (str): The new IP address to be updated in the Gist.

    Returns:
    - bool: True if the Gist was successfully updated, False otherwise.
    """
    token = read_token_from_file(TOKEN_FILE)  # Read token from file
    if not token:
        print("Failed to read Personal Access Token from file.")
        return False

    url = f"https://api.github.com/gists/{GIST_ID}"
    headers = {"Authorization": f"token {token}"}

    payload = {
        "files": {
            FILENAME: {
                "content": f'{{"ip": "{new_ip}"}}'  # Format the content as {"ip": "<new ip here>"}
            }
        }
    }

    try:
        response = requests.patch(url, headers=headers, json=payload)

        if response.status_code == 200:
            print("Gist updated successfully!")
            return True
        else:
            print(f"Failed to update Gist. Status code: {response.status_code}, Message: {response.text}")
            return False
    except requests.RequestException as e:
        print(f"Failed to update Gist: {e}")
        return False

def log_separator():
    """Print a separator line to visually separate logs."""
    print("-" * 80)

def main():
    print("Execution started at:", datetime.now())
    log_separator()

    current_ip = get_current_ip()
    if current_ip is None:
        print("Unable to fetch current IP address. Exiting.")
        log_separator()
        return

    print("Current IP address:", current_ip)
    log_separator()

    previous_ip = read_ip_from_file(IP_FILE)

    if previous_ip is None or current_ip != previous_ip:
        print("IP address has changed. Updating Gist...")
        log_separator()
        if update_gist(current_ip):
            # Update IP file with new IP
            with open(IP_FILE, "w") as file:
                file.write(current_ip)
    else:
        print("IP address has not changed. No update needed.")
        log_separator()

    print("Execution ended at:", datetime.now())
    log_separator()

if __name__ == "__main__":
    main()

@theSoberSobber
Copy link
Author

crontab -e

* * * * * /home/meso/.pyenv/shims/python /home/meso/Desktop/monitor/main.py >> /home/meso/Desktop/monitor/logs 2>&1

@theSoberSobber
Copy link
Author

use pyenv and nvm.

@theSoberSobber
Copy link
Author

2 screen, cam-enum and alertbot.

@theSoberSobber
Copy link
Author

Scp Script
Remember to specify username and port number in the below script

# Check if the correct number of arguments is provided
if ($args.Count -ne 3) {
    Write-Host "Usage: ./copy.ps1 (from|to) <source_path> <destination_path>"
    Exit
}

# Function to copy file using SCP
function Copy-FileUsingSCP {
    param(
        [string]$fromOrTo,
        [string]$sourcePath,
        [string]$destinationPath
    )

    # Fetch server JSON from GitHub Gist
    $myJson = curl "https://api.github.com/gists/844a4263a3ebc5cf8960ae12384aab90" | ConvertFrom-Json
    $newJson = $myJson.files."server.json".content | ConvertFrom-Json
    $myIp = $newJson.ip
    $username = "username"
    $port = port

    # Determine SCP source and destination paths based on 'from' or 'to'
    if ($fromOrTo -eq "from") {
        $scpSource = "$username@$myIp`:$sourcePath" # Enclosing $sourcePath in double quotes
        $scpDestination = $destinationPath
    } elseif ($fromOrTo -eq "to") {
        $scpSource = $sourcePath
        $scpDestination = "$username@$myIp`:$destinationPath" # Enclosing $destinationPath in double quotes
    } else {
        Write-Host "Invalid option. Use 'from' or 'to'."
        Exit
    }

    # Output SCP operation details
    Write-Host "Copying $scpSource to $scpDestination"

    # Perform SCP operation
    scp -P $port $scpSource $scpDestination
}

# Determine if 'from' or 'to' option is chosen
$option = $args[0]
$sourcePath = $args[1]
$destinationPath = $args[2]

# Copy file using SCP based on chosen option
if ($option -eq "from") {
    Copy-FileUsingSCP "from" $sourcePath $destinationPath
} elseif ($option -eq "to") {
    Copy-FileUsingSCP "to" $sourcePath $destinationPath
} else {
    Write-Host "Invalid option. Use 'from' or 'to'."
    Exit
}

@theSoberSobber
Copy link
Author

Public Key
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICOpceinYc2WeKwPFWvU79fySvR0NXi5mSKj51ZJ712r [email protected]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment