Simple SFTP

Simple SFTP Integration to copy files from SFTP Server using paramiko.

Utilities · Simple SFTP

Details

IDSimple SFTP
ProviderOpen Source
CategoryUtilities
From Version6.2.0
Docker Imagedemisto/netmiko:1.0.0.9067966
Supported ModulesAgentix XSIAM

README

sftp-listdir


List Directories SFTP command given directory path. Defaults to current directory upon sftp login.

Base Command

sftp-listdir

Input

Argument Name Description Required
directory The directory from which to list the all directories. Default is .. Optional

Context Output

There is no context output for this command.

sftp-copyfrom


Copies contents of file specified from the sftp server and prints it to the war room

Base Command

sftp-copyfrom

Input

Argument Name Description Required
file_path Please provide file path as seen by the sftp user upon login. Required
return_file Defaults to False where text based file content will be printed. Please specify as True to download the file in case of non-text based files. Possible values are: True, False. Default is False. Optional

Context Output

There is no context output for this command.

sftp-upload-file


Uploads a file from the War Room using it’s Entry ID to the SFTP Server at a given path

Base Command

sftp-upload-file

Input

Argument Name Description Required
path Destination path on SFTP Server to upload the file to Required
file_entry_id War-room Entry ID for the file to upload Required

Context Output

There is no context output for this command.

Configuration parameters

  • host — Host (required)
  • proxy — Use system proxy settings
  • authentication — Username (required)
  • port — Port

Commands (3)

  • sftp-copyfrom

    Copies contents of file specified from the sftp server and prints it to the war room

  • sftp-listdir

    List Directories SFTP command given directory path. Defaults to current directory upon sftp login.

  • sftp-upload-file

    Upload a file to a path on the SFTP Server

import demistomock as demisto  # noqa: F401
from CommonServerPython import *  # noqa: F401

""" IMPORTS """


import traceback

import paramiko


def get_file_path(file_id):
    filepath_result = demisto.getFilePath(file_id)
    return filepath_result


""" MAIN FUNCTION """


def main():
    HOST = demisto.params()["host"]
    USERNAME = demisto.params()["authentication"]["identifier"]
    PASSWORD = demisto.params()["authentication"]["password"]
    PORT = int(demisto.params()["port"])

    if demisto.command() == "test-module":
        try:
            client = paramiko.Transport(HOST, PORT)
            client.connect(username=USERNAME, password=PASSWORD)
            sftp = paramiko.SFTPClient.from_transport(client)
            sftp.close()  # type: ignore
            demisto.results("ok")
        except Exception as ex:
            demisto.error(traceback.format_exc())  # print the traceback
            return_error(f"Failed to connect Error: {ex!s}")

    if demisto.command() == "sftp-listdir":
        try:
            client = paramiko.Transport(HOST, PORT)
            client.connect(username=USERNAME, password=PASSWORD)
            sftp = paramiko.SFTPClient.from_transport(client)
            directory = demisto.args()["directory"]
            res = sftp.listdir(path=directory)  # type: ignore
            entry = {
                "Type": entryTypes["note"],
                "ContentsFormat": formats["text"],
                "Contents": res,
                "ReadableContentsFormat": formats["markdown"],
                "HumanReadable": tableToMarkdown("The directory files:", res, ["Directory Files"]),
                "EntryContext": {"SFTP.ListDir": res},
            }
            demisto.results(entry)
            sftp.close()  # type: ignore
        except Exception as ex:
            demisto.error(traceback.format_exc())  # print the traceback
            return_error(f"Error occurred - Error: {ex!s}. Please verify directory path to list files")

    elif demisto.command() == "sftp-copyfrom":
        try:
            client = paramiko.Transport(HOST, PORT)
            client.connect(username=USERNAME, password=PASSWORD)
            sftp = paramiko.SFTPClient.from_transport(client)
            file_path = demisto.args()["file_path"]
            sftp.get(file_path, "/tmp/" + file_path[file_path.rindex("/") + 1 :])  # type: ignore
            sftp.close()  # type: ignore
            with open("/tmp/" + file_path[file_path.rindex("/") + 1 :]) as f:
                data = f.read()
                if demisto.args()["return_file"] == "True":
                    demisto.results(fileResult(filename=file_path[file_path.rindex("/") + 1 :], data=data))
                else:
                    entry = {
                        "Type": entryTypes["note"],
                        "ContentsFormat": formats["text"],
                        "Contents": data,
                        "ReadableContentsFormat": formats["text"],
                        "HumanReadable": data,
                        "EntryContext": {"SFTP.File.Content": data},
                    }
                    demisto.results(entry)
        except Exception as ex:
            demisto.error(traceback.format_exc())  # print the traceback
            return_error(f"Error occurred - Error: {ex!s}")

    elif demisto.command() == "sftp-upload-file":
        try:
            args = demisto.args()
            client = paramiko.Transport(HOST, PORT)
            client.connect(username=USERNAME, password=PASSWORD)
            sftp = paramiko.SFTPClient.from_transport(client)
            file_path = get_file_path(args.get("file_entry_id"))
            sftp.put(file_path["path"], args.get("path") + "/" + file_path["name"])  # type: ignore
            sftp.close()  # type: ignore
            demisto.results("File uploaded successfully")
        except Exception as ex:
            demisto.error(traceback.format_exc())  # print the traceback
            return_error(f"Error occurred - Error: {ex!s}")


""" ENTRY POINT """


if __name__ in ("__main__", "__builtin__", "builtins"):
    main()