Collection of networking over sockets, using HTTP libraries, and networking
Sockets
Basic network communication over raw sockets
# Basic TCP connection to a server to send and receive dataimport socketclientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)clientsocket.connect(('127.0.0.1', 9987))clientsocket.send('hello'.encode())data = clientsocket.recv(1024)print(data)
SSH Interaction
Paramiko is a useful library which can be used to log into a host over SSH and execute commands as though it were an interactive session.
import paramikokey ='/home/some/rsa/private/key'hostname ='127.0.0.1'user ='m4lwhere'k = paramiko.RSAKey.from_private_key_file(key)ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(hostname=hostname, username=user, pkey=k)stdin, stdout, stderr = client.exec_command('ls -l')print(f'Received output:\n\n{stdout}')# Don't forget to close out the object!ssh.close()
SFTP
Paramiko can additionally support SFTP natively with a paramiko.SSHClient() object which is super cool.
import paramikokey ='/home/some/rsa/private/key'hostname ='127.0.0.1'user ='m4lwhere'k = paramiko.RSAKey.from_private_key_file(key)ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(hostname=hostname, username=user, pkey=k)sftp = ssh.open_sftp()srcFiles = sftp.listdir('/home/m4lwhere')# Download each of the files in the srcFiles listfor i in srcFiles: download =f'/home/m4lwhere/{i}' sftp.get(download, '/opt/downloads')# Upload a file from local machine to external onesftp.put('/opt/upload.txt', '/home/m4lwhere/upload.txt')ssh.close()