Sample code for 30+ languages & platforms
PureBasic

Set a Remote File's Owner and Group

See more SFTP Examples

Demonstrates the Chilkat SFtp.SetOwnerAndGroup method, which sets the owner and group of a remote item. The arguments are the remote path (or handle), whether the first argument is a handle, and the new owner and group values.

Background: This is the SFTP equivalent of chown. Changing ownership is a privileged operation on Unix systems — ordinary users generally cannot give their files away — so expect it to fail unless the authenticated account has the necessary rights. It is most often used by administrative jobs that upload files which must then belong to a service account, such as a web server user.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkSFtp.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Demonstrates the SFtp.SetOwnerAndGroup method, which sets the owner and group of a remote item.
    ;  The 1st argument is the remote path (or handle), the 2nd (isHandle) indicates which, and the
    ;  3rd and 4th are the new owner and group.

    sftp.i = CkSFtp::ckCreate()
    If sftp.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Connect, authenticate, and initialize the SFTP subsystem.
    port.i = 22
    success = CkSFtp::ckConnect(sftp,"sftp.example.com",port)
    If success = 0
        Debug CkSFtp::ckLastErrorText(sftp)
        CkSFtp::ckDispose(sftp)
        ProcedureReturn
    EndIf

    ;  Normally you would not hard-code the password in source.  You should instead obtain it
    ;  from an interactive prompt, environment variable, or a secrets vault.
    password.s = "mySshPassword"

    success = CkSFtp::ckAuthenticatePw(sftp,"mySshLogin",password)
    If success = 0
        Debug CkSFtp::ckLastErrorText(sftp)
        CkSFtp::ckDispose(sftp)
        ProcedureReturn
    EndIf

    success = CkSFtp::ckInitializeSftp(sftp)
    If success = 0
        Debug CkSFtp::ckLastErrorText(sftp)
        CkSFtp::ckDispose(sftp)
        ProcedureReturn
    EndIf

    ;  The 1st argument is a path, so isHandle is 0.  Changing ownership typically requires
    ;  elevated privileges on the server.
    isHandle.i = 0
    success = CkSFtp::ckSetOwnerAndGroup(sftp,"subdir/report.pdf",isHandle,"www-data","www-data")
    If success = 0
        Debug CkSFtp::ckLastErrorText(sftp)
        CkSFtp::ckDispose(sftp)
        ProcedureReturn
    EndIf

    Debug "Owner and group set."

    CkSFtp::ckDisconnect(sftp)


    CkSFtp::ckDispose(sftp)


    ProcedureReturn
EndProcedure