# Python SFTP Script

{% code overflow="wrap" %}

```python
import paramiko
import os

# SFTP credentials and connection details
username = 'USERNAME_HERE'
host = 'SFTP_HOST_NAME_HERE'
private_key_path = 'PATH_TO_PRIVATE_RSA_KEY'  # Update this with the path to your private key

# Directory containing files to upload
local_directory = './PATH_TO_FOLDER'  # Update this with the path to the directory containing your files

def sftp_upload_files(local_directory):
    # Create an SFTP client
    try:
        # Create SSH client
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Load the private key
        private_key = paramiko.RSAKey.from_private_key_file(private_key_path)

        # Connect to the SFTP server
        ssh.connect(host, username=username, pkey=private_key)

        # Open an SFTP session
        sftp = ssh.open_sftp()

        # Iterate over all files in the local directory
        for filename in os.listdir(local_directory):
            local_filepath = os.path.join(local_directory, filename)
            
            if os.path.isfile(local_filepath):
                try:
                    # Upload each file to the SFTP server
                    remote_filepath = f'./{filename}'  # Adjust the remote path as needed
                    sftp.put(local_filepath, remote_filepath)
                    print(f'Successfully uploaded {filename} to {remote_filepath}')
                except Exception as e:
                    print(f'Failed to upload {filename}: {e}')

        # Close the SFTP session and SSH connection
        sftp.close()
        ssh.close()

    except Exception as e:
        print(f'Failed to connect to the SFTP server: {e}')

# Call the function to upload files
sftp_upload_files(local_directory)
```

{% endcode %}

#### Key Points:

1. **Dependencies**:
   * The script relies on the `paramiko` module to handle SSH and SFTP connections and the `os` module to interact with the local file system.
2. **SFTP Connection Details**:
   * It establishes an SFTP connection using SSH credentials. The username and host are hardcoded, while the private key file is used for authentication.
3. **Local Directory**:
   * The `local_directory` variable is set to point to the folder containing files that need to be uploaded. This path is customizable.
4. **Functionality**:
   * The script defines a function `sftp_upload_files` that:
     1. Initializes an SSH client.
     2. Loads the private key from the specified file.
     3. Connects to the remote SFTP server.
     4. Opens an SFTP session.
     5. Iterates over all the files in the specified local directory.
     6. For each file, uploads it to the remote server.
     7. After all files are uploaded, the SFTP and SSH sessions are closed.
5. **Error Handling**:
   * Errors related to SFTP connection issues or file uploads are caught and printed to the console. This ensures that if something goes wrong during the process, a message is displayed.
6. **Example Workflow**:
   * When the script is executed, it uploads each file from the local\_directory directory to the remote server using the specified private key for authentication. For each successful upload, a confirmation message is printed. If any errors occur during the connection or upload process, they are caught and reported.


---

# 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://www.battlecoder.com/battlecoder/python/python-sftp-script.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.
