1 /*
2  * connect_ssh.c
3  * This file contains an example of how to connect to a
4  * SSH server using libssh
5  */
6 
7 /*
8 Copyright 2009 Aris Adamantiadis
9 
10 This file is part of the SSH Library
11 
12 You are free to copy this file, modify it in any way, consider it being public
13 domain. This does not apply to the rest of the library though, but it is
14 allowed to cut-and-paste working code from this file to any license of
15 program.
16 The goal is to show the API in action. It's not a reference on how terminal
17 clients must be made or how a client should react.
18  */
19 
20 #include <libssh/libssh.h>
21 #include "examples_common.h"
22 #include <stdio.h>
23 
connect_ssh(const char * host,const char * user,int verbosity)24 ssh_session connect_ssh(const char *host, const char *user,int verbosity){
25   ssh_session session;
26   int auth=0;
27 
28   session=ssh_new();
29   if (session == NULL) {
30     return NULL;
31   }
32 
33   if(user != NULL){
34     if (ssh_options_set(session, SSH_OPTIONS_USER, user) < 0) {
35       ssh_free(session);
36       return NULL;
37     }
38   }
39 
40   if (ssh_options_set(session, SSH_OPTIONS_HOST, host) < 0) {
41     ssh_free(session);
42     return NULL;
43   }
44   ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
45   if(ssh_connect(session)){
46     fprintf(stderr,"Connection failed : %s\n",ssh_get_error(session));
47     ssh_disconnect(session);
48     ssh_free(session);
49     return NULL;
50   }
51   if(verify_knownhost(session)<0){
52     ssh_disconnect(session);
53     ssh_free(session);
54     return NULL;
55   }
56   auth=authenticate_console(session);
57   if(auth==SSH_AUTH_SUCCESS){
58     return session;
59   } else if(auth==SSH_AUTH_DENIED){
60     fprintf(stderr,"Authentication failed\n");
61   } else {
62     fprintf(stderr,"Error while authenticating : %s\n",ssh_get_error(session));
63   }
64   ssh_disconnect(session);
65   ssh_free(session);
66   return NULL;
67 }
68