# -*- coding: utf-8 -*- """siteaccess.py - lets Claude (or another AI assistant) work on a website's files and WordPress/MySQL database from the owner's own computer. Published by Budget Web Design: https://budgetwebdesign.com.au/connect-claude/ WHAT IT DOES * Reads the login details from access.txt (in the project folder) each time it runs. Nothing is copied into scripts, chat, memory or logs, and this module never prints a password. * Files: SFTP over SSH where the host allows it (encrypted), else FTP over TLS, else plain FTP with a warning. The object returned by ftp() always speaks the ftplib methods (nlst, mlsd, retrbinary, storbinary, rename, delete, size, mkd, rmd, quit). Paths are written the FTP way: /public_html/index.php * Database: an SSH tunnel to the server's MySQL (most cPanel hosts allow the tunnel even with shell access off). For WordPress the database name, user, password and table prefix are read from wp-config.php on the server; for other sites they come from the "Database" lines of access.txt. If the host refuses SSH, get_conn() says so. * The server's SSH identity is recorded in known_hosts next to this file on first contact and checked on every later connection; a changed key stops the connection. access.txt (one "Label: value" per line; lines that do not apply can be left out): Site address: https://www.example.com.au Host: ftp.example.com.au Username: exampleuser Password: ........ Remote path: /public_html Database name: exampleuser_wp Database username: exampleuser_wp Database password: ........ NEEDS Python 3.8+ and: pip install paramiko pymysql USE from siteaccess import Site site = Site('access.txt') f = site.ftp(); print(f.nlst(site.remote_path)); f.quit() # files copy = site.backup('/public_html/wp-content/themes/mytheme/style.css') # local copy BEFORE changing a file ssh, cn, prefix = site.get_conn() # database + WordPress table prefix cur = cn.cursor(); cur.execute('SELECT option_value FROM %soptions WHERE option_name=%%s' % prefix, ('siteurl',)) ...; cn.commit(); cn.close(); ssh.close() # writes need cn.commit() python -X utf8 siteaccess.py access.txt -> connection test (prints host, user, path, files OK, database OK) RULES FOR THE ASSISTANT - The module reads the login details from access.txt each time it runs. Never print, copy or store them (not in scripts, chat, memory or logs). Do not print the contents of access.txt or wp-config.php. - Never type a password into a web login page (wp-admin, cPanel). The owner signs in. - Before changing any file or database content, save a copy of the old version in the site folder and tell the owner where it is. - Database writes need cn.commit(). Run Python with -X utf8. - If get_conn() says SSH is refused, that host has no database tunnel: use FTP only and ask the owner for anything that needs phpMyAdmin. """ import datetime import ftplib import io import os import re import sys HERE = os.path.dirname(os.path.abspath(__file__)) KNOWN_HOSTS = os.path.join(HERE, 'known_hosts') _LABELS = ( # (field, section it belongs to or None, accepted labels) ('site', None, ('site address', 'site', 'website', 'website address', 'web address', 'url', 'domain')), ('host', 'files', ('host', 'ftp host', 'sftp host', 'hosting host', 'server', 'ftp server', 'hostname', 'host name')), ('user', 'files', ('username', 'user', 'user name', 'ftp username', 'ftp user', 'hosting username', 'cpanel username', 'login')), ('password', 'files', ('password', 'pass', 'ftp password', 'hosting password', 'cpanel password')), ('remote_path', 'files', ('remote path', 'path', 'folder', 'website folder', 'document root', 'directory')), ('db_name', 'db', ('database name', 'database', 'db name', 'db', 'name')), ('db_user', 'db', ('database username', 'database user', 'db username', 'db user', 'username', 'user')), ('db_password', 'db', ('database password', 'db password', 'db pass', 'password', 'pass')), ('db_host', 'db', ('database host', 'db host')), ) def _parse(path): """'Label: value' lines. A heading line (FTP / Hosting / Database / WordPress) sets which login the plain 'Username' and 'Password' lines under it belong to; a WordPress admin login is ignored (never used here).""" out, section = {}, 'files' for raw in open(path, encoding='utf-8-sig', errors='replace'): line = raw.strip() if not line or line.startswith('#'): continue m = re.match(r'^([A-Za-z][A-Za-z ._/-]{0,40}?)\s*[:=]\s*(.*)$', line) if not m or not m.group(2).strip(): low = line.lower().rstrip(':= ') if 'database' in low or low in ('db', 'mysql'): section = 'db' elif 'wordpress' in low or 'wp-admin' in low or 'wp admin' in low: section = 'wp' elif any(k in low for k in ('ftp', 'hosting', 'cpanel', 'server')): section = 'files' continue label = re.sub(r'[^a-z ]+', ' ', m.group(1).lower()) label, value = re.sub(r'\s+', ' ', label).strip(), m.group(2).strip() if label.startswith(('wordpress', 'wp ')): continue explicit = label.startswith(('database', 'db', 'ftp', 'sftp', 'hosting', 'cpanel', 'site', 'web', 'remote')) for field, sec, names in _LABELS: if label in names and (explicit or sec is None or sec == section) and field not in out: if not (field.startswith('db_') and not explicit and section != 'db'): out[field] = value break return out def _bare_host(v): v = re.sub(r'^[a-z]+://', '', (v or '').strip(), flags=re.I) return re.sub(r'[/:].*$', '', v).strip() def _check_host_key(host, key): """Trust the server's SSH key the first time (recorded in known_hosts next to this file); refuse ever after if the key for that host changes, which is what someone intercepting the connection would look like.""" import paramiko hk = paramiko.HostKeys() if os.path.exists(KNOWN_HOSTS): hk.load(KNOWN_HOSTS) stored = hk.lookup(host) if stored is None or key.get_name() not in stored: hk.add(host, key.get_name(), key) hk.save(KNOWN_HOSTS) print('siteaccess: recorded the SSH identity of %s in %s' % (host, KNOWN_HOSTS), file=sys.stderr) return if stored[key.get_name()] != key: raise SystemExit('siteaccess: the SSH identity of %s has CHANGED since it was recorded in %s. Not connecting. ' 'If the host was legitimately rebuilt, delete its line from that file and try again.' % (host, KNOWN_HOSTS)) class _RecordOnce: def missing_host_key(self, client, hostname, key): _check_host_key(hostname, key) client.get_host_keys().add(hostname, key.get_name(), key) class _SftpAsFtp: """SFTP wrapped in the ftplib methods. FTP-style paths like /public_html/x are relative to the home folder.""" def __init__(self, transport, sftp): self._t, self._s, self._cwd = transport, sftp, '' def _p(self, path): path = path.replace(chr(92), '/') if path.startswith('/'): return path.lstrip('/') or '.' return (self._cwd + '/' + path).strip('/') if self._cwd else path def nlst(self, path='.'): return ['%s/%s' % (path.rstrip('/'), n) if path not in ('.', '') else n for n in self._s.listdir(self._p(path))] def mlsd(self, path='.'): import stat as st for a in self._s.listdir_attr(self._p(path)): yield a.filename, {'type': 'dir' if st.S_ISDIR(a.st_mode) else 'file', 'size': str(a.st_size), 'modify': str(a.st_mtime)} def retrbinary(self, cmd, callback, blocksize=65536, rest=None): with self._s.open(self._p(cmd.split(' ', 1)[1]), 'rb') as fh: if rest: fh.seek(int(rest)) while True: chunk = fh.read(blocksize) if not chunk: break callback(chunk) return '226 Transfer complete' def storbinary(self, cmd, fp, blocksize=65536, callback=None, rest=None): with self._s.open(self._p(cmd.split(' ', 1)[1]), 'wb') as fh: while True: chunk = fp.read(blocksize) if not chunk: break fh.write(chunk) if callback: callback(chunk) return '226 Transfer complete' def rename(self, a, b): try: self._s.remove(self._p(b)) # SFTP rename does not overwrite except IOError: pass self._s.rename(self._p(a), self._p(b)) def delete(self, path): self._s.remove(self._p(path)) def size(self, path): return self._s.stat(self._p(path)).st_size def mkd(self, path): self._s.mkdir(self._p(path)) def rmd(self, path): self._s.rmdir(self._p(path)) def cwd(self, path): self._cwd = self._p(path) def pwd(self): return '/' + self._cwd def quit(self): self._s.close() self._t.close() close = quit class Site: def __init__(self, access_path='access.txt'): if not os.path.isfile(access_path): raise FileNotFoundError(access_path) self.access_path = os.path.abspath(access_path) d = _parse(access_path) self.site_address = d.get('site', '') site_host = _bare_host(self.site_address) self.hosts = [h for h in dict.fromkeys([_bare_host(d.get('host')), re.sub(r'^www\.', '', site_host)]) if h] self.host = self.hosts[0] if self.hosts else None self.user = d.get('user') self._password = d.get('password') self._db = {k[3:]: v for k, v in d.items() if k.startswith('db_')} # host documents often give the server's absolute path (/home//public_html); FTP starts in the home folder self.remote_path = re.sub(r'^/home\d*/[^/]+', '', (d.get('remote_path') or '/public_html').strip()) or '/' self._cache = {} if not (self.host and self.user and self._password): raise ValueError('access.txt needs Host (or Site address), Username and Password lines; found: ' + ', '.join(sorted(k for k in d if 'password' not in k))) # ---- files --------------------------------------------------------------------------------------------------- def ftp(self): """Encrypted where the host allows it: SFTP over SSH first, then FTP over TLS, then plain FTP (with a warning).""" mode, last = self._cache.get('mode'), None for host in ([self.host] if mode else self.hosts): if mode in (None, 'sftp'): try: import paramiko t = paramiko.Transport((host, 22)) t.banner_timeout = 20 t.start_client(timeout=20) _check_host_key(host, t.get_remote_server_key()) t.auth_password(self.user, self._password) self.host, self._cache['mode'] = host, 'sftp' return _SftpAsFtp(t, paramiko.SFTPClient.from_transport(t)) except SystemExit: raise except Exception as e: last = e if mode == 'sftp': raise if mode in (None, 'ftps'): try: f = ftplib.FTP_TLS(host, timeout=90) f.auth() f.login(self.user, self._password) f.prot_p() self.host, self._cache['mode'] = host, 'ftps' return f except Exception as e: last = e if mode == 'ftps': raise try: f = ftplib.FTP(host, timeout=90) f.login(self.user, self._password) if mode is None: print('siteaccess: %s offers neither SFTP nor FTP-TLS; using plain FTP (password and files travel ' 'unencrypted)' % host, file=sys.stderr) self.host, self._cache['mode'] = host, 'ftp' return f except Exception as e: last = e raise SystemExit('siteaccess: no file login worked for user %s on %s (%s)' % (self.user, ', '.join(self.hosts), str(last)[:80])) @property def transport(self): return self._cache.get('mode', 'not connected yet') def read(self, remote): """The remote file's bytes.""" f, buf = self.ftp(), io.BytesIO() try: f.retrbinary('RETR ' + remote, buf.write) finally: f.quit() return buf.getvalue() def write(self, remote, data): """Upload bytes (or str, sent as UTF-8) to the remote path. Call backup(remote) first.""" if isinstance(data, str): data = data.encode('utf-8') f = self.ftp() try: f.storbinary('STOR ' + remote, io.BytesIO(data)) finally: f.quit() def backup(self, remote, folder=None): """Download the remote file into backups// in the project folder; returns the local path.""" folder = folder or os.path.join(os.path.dirname(self.access_path), 'backups') stamp = datetime.datetime.now().strftime('%Y-%m-%d-%H%M%S') local = os.path.join(folder, stamp, *[p for p in remote.replace(chr(92), '/').split('/') if p not in ('', '.', '..')]) data = self.read(remote) os.makedirs(os.path.dirname(local), exist_ok=True) with open(local, 'wb') as fh: fh.write(data) return local # ---- database ------------------------------------------------------------------------------------------------ def wp_config(self): """Database settings: from wp-config.php on the server when the site is WordPress, else from access.txt.""" if 'cfg' not in self._cache: cfg = None try: src = self.read(self.remote_path.rstrip('/') + '/wp-config.php').decode('utf-8', 'replace') get = lambda k: re.search(r"define\(\s*['\"]%s['\"]\s*,\s*['\"]([^'\"]*)['\"]" % k, src).group(1) cfg = {'database': get('DB_NAME'), 'user': get('DB_USER'), 'password': get('DB_PASSWORD'), 'prefix': re.search(r"\$table_prefix\s*=\s*['\"]([^'\"]*)['\"]", src).group(1)} except SystemExit: raise except Exception: if not (self._db.get('name') and self._db.get('user') and self._db.get('password')): raise SystemExit('siteaccess: no wp-config.php in %s and no Database name / username / password lines ' 'in access.txt' % self.remote_path) cfg = {'database': self._db['name'], 'user': self._db['user'], 'password': self._db['password'], 'prefix': ''} self._cache['cfg'] = cfg return self._cache['cfg'] def get_conn(self, database=None, user=None, password=None): """(ssh_client, pymysql_connection, table_prefix). Close both when finished. Writes need cn.commit().""" import paramiko import pymysql cfg = self.wp_config() if database is None else {'database': database, 'user': user, 'password': password, 'prefix': ''} c = paramiko.SSHClient() if os.path.exists(KNOWN_HOSTS): c.load_host_keys(KNOWN_HOSTS) c.set_missing_host_key_policy(_RecordOnce()) try: c.connect(self.host, 22, self.user, self._password, look_for_keys=False, allow_agent=False, timeout=30, banner_timeout=30) c.get_transport().set_keepalive(10) ch = c.get_transport().open_channel('direct-tcpip', ('127.0.0.1', 3306), ('127.0.0.1', 0)) except SystemExit: raise except Exception as e: raise SystemExit('siteaccess: SSH to %s refused (%s): this host has no database tunnel, use FTP only and ask ' 'the owner for anything that needs phpMyAdmin' % (self.host, str(e)[:80])) cn = pymysql.connections.Connection(defer_connect=True, charset='utf8mb4', read_timeout=120, user=cfg['user'], password=cfg['password'], database=cfg['database']) cn.connect(sock=ch) return c, cn, cfg['prefix'] def _test(access_path): site = Site(access_path) print('login file :', site.access_path) print('hosts :', ', '.join(site.hosts)) print('user :', site.user) print('path :', site.remote_path) try: f = site.ftp() names = [n.rsplit('/', 1)[-1] for n in f.nlst(site.remote_path)] f.quit() print('files : OK on %s via %s, %d entries in %s' % (site.host, site.transport.upper(), len(names), site.remote_path)) except SystemExit as e: print('files : FAILED -', e) return try: ssh, cn, prefix = site.get_conn() cur = cn.cursor() cur.execute('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE()') print('database : OK via SSH tunnel, %d tables%s' % (cur.fetchone()[0], ', WordPress prefix ' + prefix if prefix else '')) cn.close() ssh.close() except SystemExit as e: print('database :', e) except Exception as e: print('database : FAILED -', str(e)[:120]) if __name__ == '__main__': _test(sys.argv[1] if len(sys.argv) > 1 else 'access.txt')