用 Python 在不開啟連結的情況下檢查處方藥短訊
Who texted me that my prescription was ready? Inspecting an SMS link in Python without opening it
文章示範用 Python 標準程式庫解析處方藥短訊中的連結,而不向連結發出請求,並列出主機名稱及網址結構上的異常。腳本會把網域與預先列出的可信網域比較,但不能判定短訊是否真實;文中的訊息和網域均為虛構。
A text says your prescription is ready and offers a link to find the store. Before working out who texted me, or whether the pharmacy really did, it's worth knowing what that link says about itself. Python's standard library can take a URL apart without ever requesting it, and the result is a short list of plain facts about where a tap would go.
Affiliation and AI note: This post is promotional editorial from the website whocallme.co.uk, drafted with AI assistance. The script below was run locally with Python 3.13.5 and the standard library only. Every message and domain in it is invented, using names reserved for examples and documentation, and the script never connects to anything. It can't tell you whether a particular text is genuine.
The source note
The page for 07478 724018 lists a mobile number with the allocation hint Hutchison 3G UK Ltd. When it was fetched for this post it showed nine searches, one user report, a Negative overall rating and a "first seen: 5 days ago" label. That label belongs to the page, not to the report, which is imported and has no known original publication date.
The report, filed as Scam/Fraud, describes a "text message sent to me telling me that my prescription was ready" at a named branch of a supermarket pharmacy, "with a link to a store locator".
That's all it says. It doesn't record whether the visitor had a prescription waiting, what the link looked like, or whether they opened it. The supermarket's name is part of the message as reported and is no evidence about who sent it. Sender IDs on texts, like caller ID on calls, can be spoofed.
Why the link is the part to look at
A prescription text is plausible on its face. Pharmacies do send collection reminders, and a store locator is an ordinary thing to include. So the wording can't settle anything. The link at least has a fixed structure, and some parts of it are routinely misread:
-
Everything before an
@is a username, not the site. Inhttps://chemist.example@collect-rx.test/, the site iscollect-rx.test. -
The hostname is read right to left.
stores.chemist.examplebelongs tochemist.example.chemist-example.testdoesn't. -
Letters that look identical may not be. A hostname with an accented or non-Latin character is sent in an ASCII form starting with
xn--. - No name at all. A bare IP address tells you nothing about who runs the server.
None of these makes a link malicious, and a link with none of them can still be harmful. They're facts to compare against what you'd expect, not a verdict.
The script
The idea is to compare each link with a short list of domains you already use, taken from letters, receipts or an app you installed yourself. Here that list holds two invented domains. The script finds links in each message, parses them with urllib.parse.urlsplit, and prints the hostname plus anything unusual.
import ipaddress
import re
from urllib.parse import urlsplit
# Domains you already use, copied from letters, cards or the app you trust.
KNOWN = ["chemist.example", "surgery.example"]
URL_RE = re.compile(
r"(?:https?://)?(?:[^\s/@]+@)?"
r"(?:(?:[^\W_](?:[\w-]*[^\W_])?\.)+[^\W\d_]{2,}|\d{1,3}(?:\.\d{1,3}){3})"
r"(?::\d+)?(?:/[^\s]*)?"
)
def find_links(text):
return [m.group(0).rstrip(".,;:!?)") for m in URL_RE.finditer(text)]
def edit_distance(a, b):
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i]
for j, cb in enumerate(b, 1):
cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
prev = cur
return prev[-1]
def inspect(raw):
parts = urlsplit(raw if "://" in raw else "http://" + raw)
host = (parts.hostname or "").rstrip(".")
flags = []
if "://" not in raw:
flags.append("no scheme (the phone will guess one)")
elif parts.scheme != "https":
flags.append("not https")
if parts.username is not None:
flags.append("text before '@' is a username, not the site")
try:
ipaddress.ip_address(host)
flags.append("bare IP address instead of a name")
except ValueError:
pass
if not host.isascii():
flags.append("non-ASCII letters; sent as " + host.encode("idna").decode())
if parts.port:
flags.append("explicit port %d" % parts.port)
known = next((d for d in KNOWN if host == d or host.endswith("." + d)), None)
if known:
verdict = "inside " + known
else:
verdict = "not a domain you listed"
label = host.split(".")[-2] if host.count(".") else host
for d in KNOWN:
k = d.split(".")[0]
dist = edit_distance(label, k)
if 0 < dist <= 2:
flags.append("%s is %d edit(s) from %s" % (label, dist, k))
elif k in label and label != k:
flags.append("contains '%s' but is a different domain" % k)
return host, verdict, flags
MESSAGES = [
"Your prescription is ready at our Riverside branch. Store finder: https://stores.chemist.example/riverside",
"Prescription ready! Find your store: https://chemist.example@collect-rx.test/locator",
"Your medicine is waiting. Locate branch: http://chemist-example.test/find?b=12",
"Ready to collect today: https://chémist.example/store",
"Collect now: https://sh.test/r8Kq2",
"Ready at branch 14. Details 192.0.2.44/rx",
]
for n, text in enumerate(MESSAGES, 1):
for link in find_links(text):
host, verdict, flags = inspect(link)
print("%d. %s" % (n, link))
print(" host: %s -> %s" % (host, verdict))
for f in flags:
print(" - " + f)
Output
This is the saved output from running the script once:
1. https://stores.chemist.example/riverside
host: stores.chemist.example -> inside chemist.example
2. https://chemist.example@collect-rx.test/locator
host: collect-rx.test -> not a domain you listed
- text before '@' is a username, not the site
3. http://chemist-example.test/find?b=12
host: chemist-example.test -> not a domain you listed
- not https
- contains 'chemist' but is a different domain
4. https://chémist.example/store
host: chémist.example -> not a domain you listed
- non-ASCII letters; sent as xn--chmist-cva.example
- chémist is 1 edit(s) from chemist
5. https://sh.test/r8Kq2
host: sh.test -> not a domain you listed
6. 192.0.2.44/rx
host: 192.0.2.44 -> not a domain you listed
- no scheme (the phone will guess one)
- bare IP address instead of a name
Reading the result
Message 1 is the only link inside a domain on the list. That doesn't make the text genuine. Anyone can send a message containing a real pharmacy's address. It only means the link leads where the wording implies, which is the minimum you'd expect.
Message 2 is the classic trick. The familiar name appears first, but it sits before the @, so the browser treats it as a username and goes to collect-rx.test.
Message 3 borrows the name inside a different domain and uses plain http. Message 4 swaps one letter for an accented one; the script shows the xn-- form that would actually be looked up, and how close the label is to the real one.
Message 5 produces no warnings at all, and that matters most. A short, unknown domain with a random-looking path gives nothing to flag, yet you still have no idea where it ends up. The only true statement is the first one: not a domain you listed. Message 6 has no domain name at all.
Limits worth knowing
This is a reading aid, not a filter. The domain check is a simple suffix comparison. A real implementation would use the Public Suffix List to find registrable domains, which matters for suffixes such as co.uk. Python's built-in idna codec follows the older IDNA 2003 rules, so a few unusual names may encode differently in a browser. The URL pattern is deliberately loose and will miss some formats. And the script says nothing about what a page would do once opened.
What to do with a text like this
The safest check doesn't involve the link at all. If you're expecting a prescription, use the pharmacy's own app, or ring the branch on a number you already have, such as one printed on a previous bag or receipt. If you aren't expecting one, there's nothing to collect.
Most UK mobile networks let you report a spam text by forwarding it to 7726 at no charge, and you can delete it afterwards.
Reading the number page
The note about this prescription text is a single anonymous, unverified report. It doesn't say who holds the number, and it can't say whether the message came from the pharmacy it named. What it offers is a comparison: someone else received a text like this from the same sender ID and chose to report it.
When a different number sends you something unexpected, you can look up reports other UK recipients have left before replying or tapping anything. Then take the link apart yourself, compare it with what you already know, and go to the pharmacy by the route you'd normally use.
來源:DEV Community · dev.to