www.libssh2.org | Daily snapshots | Mailing list archive | Docs | Examples | github

Archive Index This month's Index

Subject: sample code for using sftp file attributes

sample code for using sftp file attributes

From: John Utz <john_at_utzweb.net>
Date: Wed, 2 Feb 2011 21:25:51 -0500 (EST)


I am trying to debug some file attribute stuff with sftp and curl, so i made sure that the attribute stuff works properly with libssh2.

it does. :-)

the following code compiles and run on gentoo amd64 and OSX 10.6.

this was evolved from sftp.c


static void kbd_callback(const char *name, int name_len,
             const char *instruction, int instruction_len, int num_prompts,
             const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
             LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
             void **abstract)
  int i;
  size_t n;
  char buf[1024];
  printf("Please type response: ");
  fgets(buf, sizeof(buf), stdin);
  n = strlen(buf);
  while (n > 0 && strchr("\r\n", buf[n - 1]))
  buf[n] = 0;
  responses[0].text = strdup(buf);
  responses[0].length = n;

main(int argc, char *argv[])
  int i, iRc, iPw=0, iSck = socket(AF_INET, SOCK_STREAM, 0);

  const char *pcFprt;



  unsigned long ulAdrHst = 1 < argc ? inet_addr(argv[1]) : htonl(0x7f000001);

  struct sockaddr_in sSckIn;

  sSckIn.sin_family = AF_INET;
  sSckIn.sin_port = htons(22);
  sSckIn.sin_addr.s_addr = ulAdrHst;

  if((iRc = connect(iSck, (struct sockaddr*)(&sSckIn),
                    sizeof(struct sockaddr_in)))) goto fin;

  if((iRc = libssh2_init(0))) goto fin;

  if(!(pLS2Ses = libssh2_session_init())) goto fin;

  libssh2_session_set_blocking(pLS2Ses, 1);

  if((iRc = libssh2_session_startup(pLS2Ses, iSck))) goto fin;

  if((iRc = libssh2_userauth_keyboard_interactive(pLS2Ses, "YOURLOGIN",
                                                  &kbd_callback))) goto fin;

  if(!(pLS2FtpS = libssh2_sftp_init(pLS2Ses))) goto fin;

  if(!(pLS2FtpH = libssh2_sftp_open(pLS2FtpS, "Compile/libssh2test/main.c", LIBSSH2_FXF_READ,
                                   0))) goto fin;

  if((iRc = libssh2_sftp_fstat_ex(pLS2FtpH, &LS2Atrs, 0))) goto fin;

  printf("Stat Data: Perm=%lo\n", LS2Atrs.permissions);
  printf("Stat Data: Size=%llu\n", LS2Atrs.filesize);
  printf("Stat Data: mtime=%lu\n", LS2Atrs.mtime);
  printf("Stat Data: mtime=%s\n", asctime(localtime(&LS2Atrs.mtime)));



  if(iRc) printf("libssh2 failed: %x\n", iRc);
    libssh2_session_disconnect(pLS2Ses, "Libssh2 Finished");
  if(pLS2FtpS && !pLS2FtpH) printf("Unable to open file with SFTP: %ld\n",


  return iRc;
libssh2-devel http://cool.haxx.se/cgi-bin/mailman/listinfo/libssh2-devel
Received on 2011-02-03

the libssh2 team