Repository navigation
Expand file tree
/
Copy pathshow_users.py
More file actions
221 lines (182 loc) · 7.91 KB
/
Copy pathshow_users.py
File metadata and controls
221 lines (182 loc) · 7.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import sqlite3
import boto3
import argparse
import time
import os
import sys
import requests
from pathlib import Path
from datetime import datetime
# Path relative to where script is run, usually root of project
DB_PATH = Path("instance/sessions/sessions.db").resolve()
def get_os_browser(ua):
"""Simple heuristic to parse User-Agent string."""
ua = ua.lower()
os_name = "Unknown OS"
browser_name = "Unknown Browser"
if "windows" in ua: os_name = "Windows"
elif "macintosh" in ua or "mac os" in ua: os_name = "macOS"
elif "linux" in ua: os_name = "Linux"
elif "android" in ua: os_name = "Android"
elif "ios" in ua or "iphone" in ua or "ipad" in ua: os_name = "iOS"
if "chrome" in ua and "edge" not in ua: browser_name = "Chrome"
elif "firefox" in ua: browser_name = "Firefox"
elif "safari" in ua and "chrome" not in ua: browser_name = "Safari"
elif "edge" in ua: browser_name = "Edge"
elif "curl" in ua: browser_name = "cURL"
elif "python" in ua: browser_name = "Python Script"
return f"{os_name} / {browser_name}"
def is_bot(ua):
"""Check if User-Agent looks like a bot."""
if not ua: return False
ua = ua.lower()
bot_keywords = [
"bot", "crawl", "spider", "slurp", "facebook", "google",
"bing", "yahoo", "yandex", "baidu", "duckduck", "curl",
"python", "wget", "http-client"
]
return any(keyword in ua for keyword in bot_keywords)
def get_location_data(ip):
"""Get rich location data from IP including ISP."""
if ip in ("127.0.0.1", "localhost", "::1"):
return {"location": "Localhost", "isp": "Loopback"}
if ip.startswith("10.") or ip.startswith("192.168."):
return {"location": "Internal Network", "isp": "Private"}
try:
# Using ip-api.com (free, no key, 45 requests/min limit)
response = requests.get(f"http://ip-api.com/json/{ip}", timeout=2)
if response.status_code == 200:
data = response.json()
if data.get("status") == "success":
city = data.get("city", "Unknown City")
region = data.get("regionName", "")
country = data.get("country", "Unknown Country")
isp = data.get("isp", "") + " " + data.get("org", "")
return {
"location": f"{city}, {region} ({country})",
"isp": isp
}
except Exception:
pass
return {"location": "Unknown Location", "isp": "Unknown ISP"}
def is_hosting_provider(isp_str):
"""Check if ISP indicates a hosting provider/data center."""
if not isp_str: return False
isp_str = isp_str.lower()
# Common cloud/hosting providers that suggest non-human traffic
hosting_keywords = [
"google", "amazon", "aws", "microsoft", "azure",
"digitalocean", "hetzner", "alibaba", "tencent", "oracle",
"linode", "ovh", "vultr", "choopa", "leaseweb", "datacenter",
"hosting", "cloud", "server", "colocation", "m247", "fly.io"
]
return any(keyword in isp_str for keyword in hosting_keywords)
def show_active_users():
if not DB_PATH.exists():
print(f"❌ Database not found at {DB_PATH}")
return
try:
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
# Cleanup old users first (handling it here ensures accurate read)
# UPDATED: Keep last 7 days per user request
threshold = time.time() - (7 * 86400)
cur.execute("DELETE FROM active_users WHERE last_seen < ?", (threshold,))
conn.commit()
cur.execute("SELECT ip, ua, last_seen FROM active_users ORDER BY last_seen DESC")
rows = cur.fetchall()
# Filter bots and process data
humans = []
bots_count = 0
hosting_count = 0
# Dictionary to track IP groups (first 3 octets)
# key: subnet (e.g. "192.168.1"), value: list of full IPs
ip_groups = {}
print("🔍 Analyzing traffic sources (Last 7 Days)...")
for ip, ua, last_seen in rows:
if is_bot(ua):
bots_count += 1
continue
loc_data = get_location_data(ip)
isp = loc_data.get("isp", "")
if is_hosting_provider(isp):
# Detected as Data Center/Cloud traffic
hosting_count += 1
continue
# Group IPs by subnet (Class C /24)
subnet = ".".join(ip.split(".")[:3])
if subnet not in ip_groups:
ip_groups[subnet] = []
if ip not in ip_groups[subnet]:
ip_groups[subnet].append(ip)
humans.append((ip, ua, last_seen, loc_data))
print(f"\n👥 Real Users (Last 7 Days): {len(humans)}")
print(f" (Filtered: {bots_count} Bots, {hosting_count} Data Center/VPN IPs)")
print("-" * 165)
# Added "Shared IP" column
print(f"{'Location':<35} | {'ISP':<30} | {'Last Seen':<20} | {'Shared IP / Subnet':<25} | {'OS / Browser'}")
print("-" * 165)
for ip, ua, last_seen, loc_data in humans:
# Format: YYYY-MM-DD HH:MM:SS
# Calculate time ago roughly for "Last Seen" context if needed, but date is fine.
time_str = datetime.fromtimestamp(last_seen).strftime('%Y-%m-%d %H:%M')
os_browser = get_os_browser(ua)
location = loc_data["location"]
isp = loc_data.get("isp", "Unknown")
# Truncate ISP if too long
if len(isp) > 28:
isp = isp[:25] + "..."
# Check for shared IPs
subnet = ".".join(ip.split(".")[:3])
shared_info = ""
group = ip_groups.get(subnet, [])
if len(group) > 1:
# Calculate how many OTHERS in this subnet
others = len(group) - 1
if others > 0:
shared_info = f"⚠️ Matches {others} others"
print(f"{location:<35} | {isp:<30} | {time_str:<20} | {shared_info:<25} | {os_browser}")
print("-" * 165)
conn.close()
except Exception as e:
print(f"❌ Error reading database: {e}")
def list_connect_users(instance_id, region_name=None):
"""
Lists users from a specific Amazon Connect instance.
"""
try:
# Pass region_name if provided, otherwise let boto3 resolve it
client = boto3.client('connect', region_name=region_name)
print(f"Listing users for Instance ID: {instance_id}")
if region_name:
print(f"Region: {region_name}")
users = []
next_token = None
while True:
kwargs = {
'InstanceId': instance_id,
'MaxResults': 10
}
if next_token:
kwargs['NextToken'] = next_token
response = client.list_users(**kwargs)
for user_summary in response.get('UserSummaryList', []):
users.append(user_summary)
print(f" - User: {user_summary['Username']} (ID: {user_summary['Id']})")
next_token = response.get('NextToken')
if not next_token:
break
print(f"\nTotal users found: {len(users)}")
return users
except Exception as e:
print(f"An error occurred: {e}")
return []
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Show active users or AWS Connect users.")
parser.add_argument("--connect", help="AWS Connect Instance ID to list users from", required=False)
parser.add_argument("--region", help="AWS Region (e.g., us-east-1)", required=False)
args = parser.parse_args()
if args.connect:
list_connect_users(args.connect, args.region)
else:
show_active_users()