# Networking

## Sockets

Basic network communication over raw sockets

```python
# Basic TCP connection to a server to send and receive data
import socket

clientsocket = 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.

```python
import paramiko

key = '/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.

```python
import paramiko

key = '/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 list
for i in srcFiles:
    download = f'/home/m4lwhere/{i}'
    sftp.get(download, '/opt/downloads')

# Upload a file from local machine to external one
sftp.put('/opt/upload.txt', '/home/m4lwhere/upload.txt')

ssh.close()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.m4lwhere.org/programming/python/networking.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
