An example with paramiko:
from getpass import getpass
from stat import S_IFDIR
from paramiko import SSHClient, AutoAddPolicy, SFTPAttributes
FILE = "/home/public/test.txt"
DIR = "/home/public"
HOST = "server.domain.tld"
def by_mtime(file: SFTPAttributes) -> float:
return file.st_mtime, file.filename
with SSHClient() as client:
client.set_missing_host_key_policy(AutoAddPolicy)
print("Opening ssh connection")
client.connect(HOST, username="public", password=getpass())
print("Connected")
print("opening sftp")
with client.open_sftp() as sftp:
print("Open file for writing")
with sftp.open(FILE, "wb") as fd:
fd.write(b"Hello World\n")
print("Reading written file")
with sftp.open(FILE, "rb") as fd:
text = fd.read().decode()
print(text, end="")
print("Setting chmod to 777")
sftp.chmod(FILE, 0o777)
print("Setting atime and mtime to 0 => 1970-01-01T00:00:00")
sftp.utime(FILE, (0,0))
# list all files, sorted by size
for file in sorted(sftp.listdir_iter(DIR), key=by_mtime):
# skipping directories
if file.st_mode & S_IFDIR:
continue
# only files bigger than 0 bytes
if file.st_size > 0:
print(f"{file.filename} => {file.st_size / 1024 ** 1:.1} KiB")
print("\nSFTP connection closed")
stdin, stdout, stderr = client.exec_command("uname -a")
print(stdout.read().decode())