|
import subprocess |
|
import argparse |
|
import sys |
|
import os |
|
|
|
def install_ngrok(): |
|
try: |
|
subprocess.check_output(["ngrok", "--version"]) |
|
print("ngrok is already installed.") |
|
return True |
|
except (subprocess.CalledProcessError, FileNotFoundError): |
|
print("ngrok is not found. Installing ngrok...") |
|
try: |
|
subprocess.check_output(["pip", "install", "ngrok"]) |
|
print("ngrok installed successfully.") |
|
return True |
|
except (subprocess.CalledProcessError, FileNotFoundError): |
|
print("Failed to install ngrok. Please install it manually.") |
|
return False |
|
|
|
def start_ngrok(directory): |
|
ngrok_process = subprocess.Popen(["ngrok", "http", "80"]) |
|
ngrok_ready = False |
|
public_url = "" |
|
while not ngrok_ready: |
|
ngrok_output = subprocess.check_output(["curl", "http://localhost:4040/api/tunnels"]) |
|
ngrok_output = ngrok_output.decode("utf-8") |
|
for line in ngrok_output.split("\n"): |
|
if "public_url" in line: |
|
public_url = line.split(": ")[1].strip('"') |
|
ngrok_ready = True |
|
break |
|
print("Your directory is now hosted at:") |
|
print(public_url) |
|
try: |
|
while True: |
|
pass |
|
except KeyboardInterrupt: |
|
pass |
|
ngrok_process.terminate() |
|
|
|
def main(): |
|
parser = argparse.ArgumentParser(description="Host a directory with ngrok") |
|
parser.add_argument("directory", help="Directory path to host") |
|
parser.add_argument("-i", "--install", action="store_true", help="Install ngrok if not found") |
|
args = parser.parse_args() |
|
if args.install: |
|
if not install_ngrok(): |
|
sys.exit(1) |
|
if not os.path.isdir(args.directory): |
|
print("Invalid directory path.") |
|
sys.exit(1) |
|
os.chdir(args.directory) |
|
start_ngrok(args.directory) |
|
|
|
if __name__ == "__main__": |
|
main() |