Skip to content

Instantly share code, notes, and snippets.

@Yepoleb
Created April 21, 2024 00:31
Show Gist options
  • Save Yepoleb/7baf531acbd2e54ccc7887f4a83f09f2 to your computer and use it in GitHub Desktop.
Save Yepoleb/7baf531acbd2e54ccc7887f4a83f09f2 to your computer and use it in GitHub Desktop.
import ipaddress
import os
import socket
import subprocess
def parse_ip_port(c):
ip_h, port_h = c.split(":")
return str(ipaddress.IPv4Address(socket.htonl(int(ip_h, 16)))), int(port_h, 16)
def get_socket_inode(addr_tuple):
tcp_f = open("/proc/net/tcp")
tcp_f.readline()
for line in tcp_f:
columns = line.strip().split()
remote_address = parse_ip_port(columns[1])
inode = int(columns[9])
if remote_address == addr_tuple:
return inode
def get_inode_pid(inode):
proc_l = os.listdir("/proc")
for proc_num in proc_l:
if not proc_num.isdecimal():
continue
pid = int(proc_num)
try:
fd_l = os.listdir(f"/proc/{pid}/fd")
except (PermissionError, FileNotFoundError):
continue
for fd_num in fd_l:
try:
fd_stat = os.stat(f"/proc/{pid}/fd/{fd_num}")
except FileNotFoundError:
continue
if fd_stat.st_ino == inode:
return pid
def get_pid_path(pid):
return os.readlink(f"/proc/{pid}/exe")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s.bind(("127.0.0.1", 2222))
print("Connect with 'telnet 127.0.0.1 2222'")
s.listen()
while True:
conn, peer = s.accept()
print("Peer address", peer)
inode = get_socket_inode(peer)
print("Inode", inode)
pid = get_inode_pid(inode)
print("PID", pid)
path = get_pid_path(pid)
print("Path", path)
subprocess.run(["file", path])
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment