Forum Discussion

Kody's avatar
2 years ago

Monitor SFTP site connection

Has someone already created a data source that checks a SFTP connection to a specific site?  I saw there was one created a few years ago but the link is dead.

5 Replies

  • Chat-GPT to the rescue:

    @Grab('com.jcraft:jsch:0.1.55')
    import com.jcraft.jsch.*

    // Set the SFTP server connection details
    def host = "example.com"
    def port = 22
    def username = "username"
    def password = "password"

    // Set the file name to be read
    def fileName = "example.txt"

    // Create a JSch session
    JSch jsch = new JSch()
    Session session = jsch.getSession(username, host, port)
    session.setPassword(password)
    session.setConfig("StrictHostKeyChecking", "no")
    session.connect()

    // Create an SFTP channel and connect it to the session
    ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp")
    sftpChannel.connect()

    // List the contents of the default directory
    def files = sftpChannel.ls(".")
    println("Files in default directory:")
    files.each { file ->
    println(file.filename)
    }

    // Print the contents of the file with the given file name
    try {
    InputStream inputStream = sftpChannel.get(fileName)
    println("Contents of file $fileName:")
    println(inputStream.text)
    } catch (SftpException e) {
    println("File $fileName not found")
    }

    // Disconnect the SFTP channel and session
    sftpChannel.disconnect()
    session.disconnect()

    Although, you don’t need to Grab on the first line because jsch is already installed on the collector. This is eerily close to the example in monitoring-recipes. Hopefully between the two, creating a new scripted datasource won’t be out of reach. Let me know how it goes.

  • Do you just want to know that the port is open and accepting connections on a TCP level? Or do you want to do more (authenticate, look for a file, check a file size/contents)?

  • Chat-GPT prompt FYI:

    Write a Groovy script to connect to a given SFTP server, log in using a given user name and password, list the contents of the default directory, and print the contents of a file with a given file name. If the file with the given file name is not present, print a message indicating that.

  • Thanks I will take a look at this.  All I need it to do for now is make sure an account can be authenticated.

  • In that case, you could take out the two code blocks that start with:

    // Print the contents of the file with the given file name
    // List the contents of the default directory