• First and foremost, this is a bad Idea
  • Secondly, this will work
  • Python will be able to extend the scripts more 
  • This should eliminate take-down requests as DNS exists outside of the scope of most law-enforcement mechanisms

DNS Schema for Torrent Magnet Links using Python in BIND

Ok, I cannot stress enough how much of a bad Idea this is, like awful, bad, please don’t do it, ever, and if you do, and you break the internet, I will not be happy.

But this is based on a Blue sky Thread I saw the other day, and I couldn’t get it out of my head, so here y’all are, in it’s full glory.

This also allows links to be replicated and stored in a way that provides distributed load and replication across dns servers that own the record, and since there’s no fancy UI being generated by a webserver, it can run on ANYTHING down to a microcontroller with enough storage.

I’m also marking this one as public so it can be seen.


  1. The layout and record types are TXT and leverage the fact that you can store 4096 bytes in a TXT record.
  2. I do recommend, if you do this, to use a subdomain, that is set to a very long TTL
  3. The subdomain should also be under an SRV domain type, such as 
    1. magents.domain.com SRV 
    2. This is an afterthought of this implementation, but It would help distinguish the magnets from the web content and standardize the implementation

DNS Schema for Torrent Magnet Links using Python in BIND

To implement a scheme for storing information in TXT records in the DNS as described, we can follow a structured approach to encode and retrieve the necessary data. Below is a detailed plan:


Format of the TXT Record

Each TXT record will use a key-value format to make it easy to parse. Here’s how the data can be structured:

Record Name

  • tmdb-00000000: This is the name of the record, where 00000000 is a placeholder for the unique TMDb ID.
    • Example: tmdb-12345678.

TXT Record Content

  1. For TV Episodes:
    magnet:<torrent_magnet_link>|episode:s01e01|language:en|quality:1080p
    
    • magnet:<torrent_magnet_link>: Encodes the torrent magnet link.
    • episode:s01e01: Indicates the season and episode.
    • language:<lang_code>: Specifies the language code (e.g., en for English).
    • quality:<resolution>: Specifies the quality of the torrent (e.g., 1080p, 720p).
  2. For Movies:
    magnet:<torrent_magnet_link>|movie:<title>|language:en|quality:1080p
    
    • movie:<title>: Encodes the movie title.

Example Records

TV Episode:

  • Record Name: tmdb-12345678
  • TXT Record:
    "magnet:?xt=urn:btih:12345abcdef...|episode:s01e01|language:en|quality:1080p"
    

Movie:

  • Record Name: tmdb-87654321
  • TXT Record:
    "magnet:?xt=urn:btih:abcdef12345...|movie:Inception|language:en|quality:1080p"
    

Implementation Steps

  1. Creating the Record:
    • Use DNS management tools (e.g., BIND, AWS Route 53, or Cloudflare) to create TXT records with the structured format.
    • Split magnet links longer than 255 characters into multiple quoted strings.
  2. Parsing the Record:
    • When querying the DNS record, concatenate all strings returned by the TXT record query.
    • Parse the record into key-value pairs using a delimiter (e.g., |).
  3. Querying the Record:
    • Use a DNS query tool (e.g., dig or a DNS library in your programming language) to fetch the TXT record.

Advantages

  • Scalable: Records are independent and can be added for each unique TMDb ID.
  • DNS Caching: Records benefit from DNS caching, reducing lookup overhead for repeated queries.
  • Structured Format: Key-value encoding ensures ease of parsing.

Considerations

  • Size Limit: Ensure the total TXT record does not exceed 4,096 bytes.
  • Privacy: Public DNS records are accessible to anyone, so consider encryption or obfuscation if sensitive data is stored.
  • Updates: Changes to DNS records may take time to propagate due to TTL settings.

Setup the records using BIND

To set up DNS TXT records for storing the specified data using BIND, follow these step-by-step instructions:

DNS Schema for Torrent Magnet Links using Python in BIND


1. Install and Configure BIND

On a Linux system:

  1. Install BIND:
    sudo apt update
    sudo apt install bind9 bind9utils bind9-doc
    
  2. Ensure BIND is running:
    sudo systemctl enable bind9
    sudo systemctl start bind9
    
  3. Confirm BIND installation:
    named -v
    

2. Define Your Domain Zone

Add a new zone for your domain in the BIND configuration file (/etc/bind/named.conf.local):

zone "example.com" {
    type master;
    file "/etc/bind/zones/db.example.com";
};
  • Replace example.com with your domain name.
  • Ensure the zones directory exists:
    sudo mkdir -p /etc/bind/zones
    

3. Create the Zone File

Create and edit the zone file /etc/bind/zones/db.example.com:

sudo nano /etc/bind/zones/db.example.com

Add the following content to the zone file:

$TTL    86400
@       IN      SOA     ns1.example.com. admin.example.com. (
                        2024112101 ; Serial
                        3600       ; Refresh
                        1800       ; Retry
                        1209600    ; Expire
                        86400 )    ; Minimum TTL

        IN      NS      ns1.example.com.

tmdb-12345678    IN      TXT     "magnet:?xt=urn:btih:abcdef12345...|episode:s01e01|language:en|quality:1080p"
tmdb-87654321    IN      TXT     "magnet:?xt=urn:btih:12345abcdef...|movie:Inception|language:en|quality:1080p"
  • Replace ns1.example.com. with your nameserver’s hostname.
  • Replace the magnet links and metadata with actual data.
  • Split any content over 255 characters into multiple quoted strings:

tmdb-99999999 IN TXT (“magnet:?xt=urn:btih:abcdef12345…|” “episode:s01e01|language:en|quality:1080p”)


---

### **4. Check Configuration**
1. **Verify zone file syntax**:
 ```bash
 named-checkzone example.com /etc/bind/zones/db.example.com
  1. Check BIND configuration syntax:
    named-checkconf
    

5. Reload BIND

  1. Restart or reload BIND to apply the changes:
    sudo systemctl reload bind9
    
  2. Verify that the service is running without issues:
    sudo systemctl status bind9
    

6. Test the Setup

Use the dig tool to query your TXT records:

dig @<your_server_ip> tmdb-12345678.example.com TXT
  • Replace <your_server_ip> with your DNS server’s IP address.
  • The response should include the TXT record with the magnet link and metadata.

7. Automating Updates (Optional)

For frequent updates, you can use a script to programmatically update the zone file and reload BIND:

  1. Use a Python or Bash script to:
    • Add new tmdb-<ID> entries.
    • Increment the zone file’s Serial number.
  2. Reload BIND after updating:
    sudo rndc reload example.com
    

Notes

  • Ensure your DNS server is properly secured, and only authorized users can update the zone files.
  • Use appropriate TTL values to balance caching and update propagation times.
  • If managing a public DNS server, consider privacy implications of storing magnet links.

Automate adding the DNS TXT records using python


XML File Format

Assume your XML file (data.xml) contains the following structure:

<records>
    <record>
        <tmdb_id>12345678</tmdb_id>
        <type>episode</type>
        <magnet>magnet:?xt=urn:btih:abcdef12345...</magnet>
        <details>s01e01</details>
        <language>en</language>
        <quality>1080p</quality>
    </record>
    <record>
        <tmdb_id>87654321</tmdb_id>
        <type>movie</type>
        <magnet>magnet:?xt=urn:btih:12345abcdef...</magnet>
        <details>Inception</details>
        <language>en</language>
        <quality>720p</quality>
    </record>
</records>

Python Script

Save the following script as update_dns.py:

import xml.etree.ElementTree as ET
import re
import os

# Configurations
ZONE_FILE = "/etc/bind/zones/db.example.com"
XML_FILE = "data.xml"
DOMAIN = "example.com"

def parse_xml(file_path):
    """Parse XML file and return a list of records."""
    tree = ET.parse(file_path)
    root = tree.getroot()
    records = []
    for record in root.findall('record'):
        tmdb_id = record.find('tmdb_id').text
        record_type = record.find('type').text
        magnet = record.find('magnet').text
        details = record.find('details').text
        language = record.find('language').text
        quality = record.find('quality').text
        records.append({
            'tmdb_id': tmdb_id,
            'type': record_type,
            'magnet': magnet,
            'details': details,
            'language': language,
            'quality': quality
        })
    return records

def increment_serial(zone_file):
    """Increment the serial number in the zone file."""
    with open(zone_file, 'r') as file:
        lines = file.readlines()

    for i, line in enumerate(lines):
        if re.search(r'; Serial', line):
            parts = line.strip().split(';')
            serial = int(parts[0].strip())
            new_serial = str(serial + 1).zfill(len(parts[0].strip()))
            lines[i] = f"{new_serial} ; Serial\n"
            break

    with open(zone_file, 'w') as file:
        file.writelines(lines)

def update_zone_file(zone_file, records):
    """Update the BIND zone file with new TXT records."""
    with open(zone_file, 'r') as file:
        lines = file.readlines()

    # Find the start of TXT records section
    start_idx = next((i for i, line in enumerate(lines) if "IN NS" in line), None) + 1

    # Create new TXT records
    txt_records = []
    for record in records:
        if record['type'] == 'episode':
            content = f"magnet:{record['magnet']}|episode:{record['details']}|language:{record['language']}|quality:{record['quality']}"
        elif record['type'] == 'movie':
            content = f"magnet:{record['magnet']}|movie:{record['details']}|language:{record['language']}|quality:{record['quality']}"
        
        # Split long lines into 255-character chunks
        chunks = [content[i:i+255] for i in range(0, len(content), 255)]
        quoted_chunks = ' '.join(f'"{chunk}"' for chunk in chunks)
        txt_record = f"tmdb-{record['tmdb_id']} IN TXT {quoted_chunks}\n"
        txt_records.append(txt_record)

    # Replace or append new TXT records
    lines = lines[:start_idx] + txt_records + ["\n"]

    with open(zone_file, 'w') as file:
        file.writelines(lines)

def reload_bind():
    """Reload BIND service to apply changes."""
    os.system("sudo rndc reload")

def main():
    # Parse XML
    records = parse_xml(XML_FILE)
    print(f"Parsed {len(records)} records from XML.")

    # Update zone file
    increment_serial(ZONE_FILE)
    update_zone_file(ZONE_FILE, records)
    print(f"Updated zone file: {ZONE_FILE}")

    # Reload BIND
    reload_bind()
    print("Reloaded BIND service.")

if __name__ == "__main__":
    main()

How to Use

  1. Prepare Files:
    • Save the XML file as data.xml in the same directory as the script.
    • Ensure the ZONE_FILE path in the script matches your zone file location.
  2. Run the Script:
    sudo python3 update_dns.py
    
  3. Verify Changes: After running the script, use dig to check the updated records:
    dig @<your_dns_server_ip> tmdb-12345678.example.com TXT
    

Features

  • Parses XML: Extracts and formats data for DNS TXT records.
  • Handles Long Records: Splits long TXT content into chunks (max 255 characters).
  • Automates Serial Increment: Updates the zone file serial number.
  • Reloads BIND: Applies changes without restarting the server.

Bonus: How to Add the information of an Album using the Gracenote ID

To support music files and albums using a Gracenote ID, we can extend the XML format and Python script. 


Updated XML File Format

We will add support for music files and albums with a <music> tag in the XML. For Gracenote, we use gn_id to identify the records.

<records>
    <record>
        <tmdb_id>12345678</tmdb_id>
        <type>episode</type>
        <magnet>magnet:?xt=urn:btih:abcdef12345...</magnet>
        <details>s01e01</details>
        <language>en</language>
        <quality>1080p</quality>
    </record>
    <record>
        <tmdb_id>87654321</tmdb_id>
        <type>movie</type>
        <magnet>magnet:?xt=urn:btih:12345abcdef...</magnet>
        <details>Inception</details>
        <language>en</language>
        <quality>720p</quality>
    </record>
    <record>
        <gn_id>ABCDE12345</gn_id>
        <type>album</type>
        <magnet>magnet:?xt=urn:btih:78910abcdef...</magnet>
        <title>Thriller</title>
        <artist>Michael Jackson</artist>
        <quality>FLAC</quality>
    </record>
    <record>
        <gn_id>FGHIJ67890</gn_id>
        <type>track</type>
        <magnet>magnet:?xt=urn:btih:11223344...</magnet>
        <title>Billie Jean</title>
        <artist>Michael Jackson</artist>
        <quality>MP3</quality>
    </record>
</records>

Updated Python Script

Here’s the updated script with support for Gracenote records:

import xml.etree.ElementTree as ET
import re
import os

# Configurations
ZONE_FILE = "/etc/bind/zones/db.example.com"
XML_FILE = "data.xml"
DOMAIN = "example.com"

def parse_xml(file_path):
    """Parse XML file and return a list of records."""
    tree = ET.parse(file_path)
    root = tree.getroot()
    records = []
    for record in root.findall('record'):
        record_data = {}
        for child in record:
            record_data[child.tag] = child.text
        records.append(record_data)
    return records

def increment_serial(zone_file):
    """Increment the serial number in the zone file."""
    with open(zone_file, 'r') as file:
        lines = file.readlines()

    for i, line in enumerate(lines):
        if re.search(r'; Serial', line):
            parts = line.strip().split(';')
            serial = int(parts[0].strip())
            new_serial = str(serial + 1).zfill(len(parts[0].strip()))
            lines[i] = f"{new_serial} ; Serial\n"
            break

    with open(zone_file, 'w') as file:
        file.writelines(lines)

def create_txt_record(record):
    """Create a TXT record string for a given record."""
    if record['type'] == 'episode':
        content = f"magnet:{record['magnet']}|episode:{record['details']}|language:{record['language']}|quality:{record['quality']}"
        key = f"tmdb-{record['tmdb_id']}"
    elif record['type'] == 'movie':
        content = f"magnet:{record['magnet']}|movie:{record['details']}|language:{record['language']}|quality:{record['quality']}"
        key = f"tmdb-{record['tmdb_id']}"
    elif record['type'] == 'album':
        content = f"magnet:{record['magnet']}|album:{record['title']}|artist:{record['artist']}|quality:{record['quality']}"
        key = f"gn-{record['gn_id']}"
    elif record['type'] == 'track':
        content = f"magnet:{record['magnet']}|track:{record['title']}|artist:{record['artist']}|quality:{record['quality']}"
        key = f"gn-{record['gn_id']}"
    else:
        raise ValueError(f"Unsupported record type: {record['type']}")

    # Split long lines into 255-character chunks
    chunks = [content[i:i+255] for i in range(0, len(content), 255)]
    quoted_chunks = ' '.join(f'"{chunk}"' for chunk in chunks)
    return f"{key} IN TXT {quoted_chunks}\n"

def update_zone_file(zone_file, records):
    """Update the BIND zone file with new TXT records."""
    with open(zone_file, 'r') as file:
        lines = file.readlines()

    # Find the start of TXT records section
    start_idx = next((i for i, line in enumerate(lines) if "IN NS" in line), None) + 1

    # Create new TXT records
    txt_records = [create_txt_record(record) for record in records]

    # Replace or append new TXT records
    lines = lines[:start_idx] + txt_records + ["\n"]

    with open(zone_file, 'w') as file:
        file.writelines(lines)

def reload_bind():
    """Reload BIND service to apply changes."""
    os.system("sudo rndc reload")

def main():
    # Parse XML
    records = parse_xml(XML_FILE)
    print(f"Parsed {len(records)} records from XML.")

    # Update zone file
    increment_serial(ZONE_FILE)
    update_zone_file(ZONE_FILE, records)
    print(f"Updated zone file: {ZONE_FILE}")

    # Reload BIND
    reload_bind()
    print("Reloaded BIND service.")

if __name__ == "__main__":
    main()

How It Works

  1. Parsing Records:
    • The XML format now includes support for albums (type: album) and tracks (type: track).
    • Records are identified by gn_id for music and tmdb_id for movies/TV episodes.
  2. TXT Record Generation:
    • The create_txt_record() function handles different record types and encodes the appropriate fields into a TXT record.
  3. Zone File Updates:
    • Existing records are replaced with new ones from the XML file.
    • Serial number is incremented to ensure the changes are applied.
  4. Reloading BIND:
    • After updating the zone file, the script reloads the BIND service.

Example Output

For the sample XML, the zone file will include:

tmdb-12345678 IN TXT "magnet:?xt=urn:btih:abcdef12345...|episode:s01e01|language:en|quality:1080p"
tmdb-87654321 IN TXT "magnet:?xt=urn:btih:12345abcdef...|movie:Inception|language:en|quality:720p"
gn-ABCDE12345 IN TXT "magnet:?xt=urn:btih:78910abcdef...|album:Thriller|artist:Michael Jackson|quality:FLAC"
gn-FGHIJ67890 IN TXT "magnet:?xt=urn:btih:11223344...|track:Billie Jean|artist:Michael Jackson|quality:MP3"

Usage

  1. Place the updated data.xml file and update_dns.py script in the same directory.
  2. Run the script:
    sudo python3 update_dns.py
    
  3. Verify the updated records using dig:
    dig @<your_dns_server_ip> gn-ABCDE12345.example.com TXT
    

Script to read back the TXT records and parse into JSON or XML

Python script that parses the output of a DNS lookup and converts it into either XML or JSON based on command-line parameters. The script uses dig to perform the DNS lookup.


Python Script

Save this script as dns_to_data.py:

import argparse
import subprocess
import xml.etree.ElementTree as ET
import json
import sys

def dns_lookup(record_id, record_type, domain):
    """Perform a DNS lookup for a TXT record."""
    dns_name = f"{record_type}-{record_id}.{domain}"
    try:
        result = subprocess.run(
            ["dig", "+short", dns_name, "TXT"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        if result.returncode != 0 or not result.stdout.strip():
            raise ValueError(f"No TXT record found for {dns_name}")
        return result.stdout.strip().replace('" "', '').replace('"', '')
    except Exception as e:
        print(f"Error performing DNS lookup: {e}", file=sys.stderr)
        sys.exit(1)

def parse_txt_record(txt_record):
    """Parse a TXT record into key-value pairs."""
    fields = txt_record.split("|")
    parsed_data = {}
    for field in fields:
        key, value = field.split(":", 1)
        parsed_data[key] = value
    return parsed_data

def generate_xml(data):
    """Convert parsed data into XML format."""
    root = ET.Element("record")
    for key, value in data.items():
        child = ET.SubElement(root, key)
        child.text = value
    return ET.tostring(root, encoding="unicode", method="xml")

def generate_json(data):
    """Convert parsed data into JSON format."""
    return json.dumps(data, indent=4)

def main():
    # Set up argument parser
    parser = argparse.ArgumentParser(description="Parse DNS TXT record into XML or JSON.")
    parser.add_argument("--id", required=True, help="The ID to lookup (e.g., TMDb ID or Gracenote ID).")
    parser.add_argument("--type", required=True, choices=["gracenote", "tmdb", "imdb"], help="The type of the record (e.g., Gracenote, TMDb, IMDB).")
    parser.add_argument("--domain", required=True, help="The domain to query.")
    parser.add_argument("--format", required=True, choices=["xml", "json"], help="Output format (xml or json).")

    args = parser.parse_args()

    # Perform DNS lookup
    txt_record = dns_lookup(args.id, args.type, args.domain)

    # Parse TXT record
    parsed_data = parse_txt_record(txt_record)

    # Generate output
    if args.format == "xml":
        output = generate_xml(parsed_data)
    elif args.format == "json":
        output = generate_json(parsed_data)

    print(output)

if __name__ == "__main__":
    main()

Usage

  1. Save the script as dns_to_data.py.
  2. Make it executable:
    chmod +x dns_to_data.py
    
  3. Run the script with appropriate parameters:
    ./dns_to_data.py --id 12345678 --type tmdb --domain example.com --format xml
    

Input Parameters

  • --id: The unique ID to look up (e.g., TMDb ID, Gracenote ID, IMDB ID).
  • --type: The type of record (gracenote, tmdb, or imdb).
  • --domain: The DNS domain to query (e.g., example.com).
  • --format: The output format (xml or json).

Example

Input Command:

./dns_to_data.py --id 12345678 --type tmdb --domain example.com --format json

DNS TXT Record (dig output):

"magnet:?xt=urn:btih:abcdef12345...|episode:s01e01|language:en|quality:1080p"

Output (json):

{
    "magnet": "?xt=urn:btih:abcdef12345...",
    "episode": "s01e01",
    "language": "en",
    "quality": "1080p"
}

Dependencies

  • Python 3.6+ (for argparse and json modules).
  • dig command-line utility for DNS lookups.

Customization

  • Modify dns_lookup() to support other DNS query methods if needed.
  • Add validation for DNS TXT record formatting in parse_txt_record().

Automatically pass the Link to a client

To add functionality for passing the output (e.g., magnet links) to popular torrent clients, the script will be extended to include optional integration with clients such as qBittorrent, Transmission, and Deluge.

The updated script will use appropriate APIs or command-line interfaces for each client.


Updated Python Script

Save the following updated script as dns_to_torrent.py:

import argparse
import subprocess
import xml.etree.ElementTree as ET
import json
import sys
import os

# Torrent client handlers
def send_to_qbittorrent(magnet):
    """Send magnet link to qBittorrent."""
    try:
        subprocess.run(["qbittorrent", "--", magnet], check=True)
        print("Magnet link added to qBittorrent.")
    except FileNotFoundError:
        print("qBittorrent not found. Ensure it is installed and in your PATH.")
        sys.exit(1)
    except subprocess.CalledProcessError as e:
        print(f"Error adding magnet link to qBittorrent: {e}")
        sys.exit(1)

def send_to_transmission(magnet):
    """Send magnet link to Transmission."""
    try:
        subprocess.run(["transmission-remote", "-a", magnet], check=True)
        print("Magnet link added to Transmission.")
    except FileNotFoundError:
        print("Transmission not found. Ensure it is installed and in your PATH.")
        sys.exit(1)
    except subprocess.CalledProcessError as e:
        print(f"Error adding magnet link to Transmission: {e}")
        sys.exit(1)

def send_to_deluge(magnet):
    """Send magnet link to Deluge."""
    try:
        subprocess.run(["deluge-console", f"add {magnet}"], shell=True, check=True)
        print("Magnet link added to Deluge.")
    except FileNotFoundError:
        print("Deluge not found. Ensure it is installed and in your PATH.")
        sys.exit(1)
    except subprocess.CalledProcessError as e:
        print(f"Error adding magnet link to Deluge: {e}")
        sys.exit(1)

def send_to_torrent_client(magnet, client):
    """Dispatch magnet link to the specified torrent client."""
    if client == "qbittorrent":
        send_to_qbittorrent(magnet)
    elif client == "transmission":
        send_to_transmission(magnet)
    elif client == "deluge":
        send_to_deluge(magnet)
    else:
        print(f"Unsupported torrent client: {client}")
        sys.exit(1)

# Core functionality
def dns_lookup(record_id, record_type, domain):
    """Perform a DNS lookup for a TXT record."""
    dns_name = f"{record_type}-{record_id}.{domain}"
    try:
        result = subprocess.run(
            ["dig", "+short", dns_name, "TXT"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        if result.returncode != 0 or not result.stdout.strip():
            raise ValueError(f"No TXT record found for {dns_name}")
        return result.stdout.strip().replace('" "', '').replace('"', '')
    except Exception as e:
        print(f"Error performing DNS lookup: {e}", file=sys.stderr)
        sys.exit(1)

def parse_txt_record(txt_record):
    """Parse a TXT record into key-value pairs."""
    fields = txt_record.split("|")
    parsed_data = {}
    for field in fields:
        key, value = field.split(":", 1)
        parsed_data[key] = value
    return parsed_data

def generate_xml(data):
    """Convert parsed data into XML format."""
    root = ET.Element("record")
    for key, value in data.items():
        child = ET.SubElement(root, key)
        child.text = value
    return ET.tostring(root, encoding="unicode", method="xml")

def generate_json(data):
    """Convert parsed data into JSON format."""
    return json.dumps(data, indent=4)

def main():
    # Set up argument parser
    parser = argparse.ArgumentParser(description="Parse DNS TXT record into XML or JSON, and optionally pass to a torrent client.")
    parser.add_argument("--id", required=True, help="The ID to lookup (e.g., TMDb ID or Gracenote ID).")
    parser.add_argument("--type", required=True, choices=["gracenote", "tmdb", "imdb"], help="The type of the record (e.g., Gracenote, TMDb, IMDB).")
    parser.add_argument("--domain", required=True, help="The domain to query.")
    parser.add_argument("--format", choices=["xml", "json"], help="Output format (xml or json).")
    parser.add_argument("--torrent-client", choices=["qbittorrent", "transmission", "deluge"], help="Send magnet link to a torrent client.")

    args = parser.parse_args()

    # Perform DNS lookup
    txt_record = dns_lookup(args.id, args.type, args.domain)

    # Parse TXT record
    parsed_data = parse_txt_record(txt_record)

    # Output in the requested format
    if args.format == "xml":
        output = generate_xml(parsed_data)
        print(output)
    elif args.format == "json":
        output = generate_json(parsed_data)
        print(output)

    # Send to torrent client if specified
    if args.torrent_client:
        if "magnet" not in parsed_data:
            print("Error: No magnet link found in the TXT record.")
            sys.exit(1)
        send_to_torrent_client(parsed_data["magnet"], args.torrent_client)

if __name__ == "__main__":
    main()

Usage

  1. Save the script as dns_to_torrent.py.
  2. Make it executable:
    chmod +x dns_to_torrent.py
    
  3. Run the script with parameters to parse DNS TXT records and optionally pass them to a torrent client.

Examples

1. Convert DNS TXT Record to JSON:

./dns_to_torrent.py --id 12345678 --type tmdb --domain example.com --format json

2. Convert DNS TXT Record to XML:

./dns_to_torrent.py --id 12345678 --type tmdb --domain example.com --format xml

3. Send Magnet Link to qBittorrent:

./dns_to_torrent.py --id 12345678 --type tmdb --domain example.com --torrent-client qbittorrent

4. Send Magnet Link to Transmission:

./dns_to_torrent.py --id 12345678 --type tmdb --domain example.com --torrent-client transmission

5. Send Magnet Link to Deluge:

./dns_to_torrent.py --id 12345678 --type tmdb --domain example.com --torrent-client deluge

Dependencies

  • Python: Ensure Python 3.6+ is installed.
  • Command-line tools:
    • qBittorrent
    • transmission-remote
    • deluge-console
  • Ensure the respective torrent client is installed and accessible in the system’s PATH.

Key Features

  • Flexible output: Generate either XML or JSON output.
  • Torrent client support: Send magnet links to qBittorrent, Transmission, or Deluge directly.
  • Error handling: Handles DNS failures, missing magnet links, and unsupported torrent clients.

Discover more from Christine Alifrangis

Subscribe to get the latest posts sent to your email.

Leave a Reply