1 /*******************************************************
2 * SSH CLIENT *
3 * *
4 * NO LICENSE, THIS CODE IS PUBLIC DOMAIN *
5 * *
6 * Written by Pioz *
7 * To compile: "gcc -o ssh_client ssh_client.c -lssh2" *
8 *******************************************************/
9
10 #include <arpa/inet.h>
11 #include <stdio.h>
12 #include <libssh2.h>
13
14
15 int
16 main (int argc, char **argv)
17 {
18 if (argc != 5)
19 {
20 fprintf (stderr, "usage: %s host user pass cmd\n", argv[0]);
21 return -1;
22 }
23
24 char *host = argv[1];
25 int port = 22;
26 char *user = argv[2];
27 char *pass = argv[3];
28 char *cmd = argv[4];
29
30 int sock;
31 LIBSSH2_SESSION *session;
32 LIBSSH2_CHANNEL *channel;
33 struct sockaddr_in sin;
34
35 // Make a connection on port 22
36 sock = socket (AF_INET, SOCK_STREAM, 0);
37 sin.sin_family = AF_INET;
38 sin.sin_port = htons (port);
39 sin.sin_addr.s_addr = inet_addr (host);
40 if (connect (sock, (struct sockaddr*)(&sin), sizeof (struct sockaddr_in)) != 0)
41 {
42 fprintf (stderr, "Connection failed!\n");
43 return -1;
44 }
45 session = libssh2_session_init ();
46 if (libssh2_session_startup (session, sock))
47 {
48 fprintf (stderr, "SSH connection failed!\n");
49 return -1;
50 }
51
52 // Authentication
53 if (libssh2_userauth_password (session, user, pass))
54 {
55 fprintf (stderr, "Authentication failed!\n");
56 return -1;
57 }
58 printf ("Authentication successfully!\n");
59
60 // Open terminal
61 if (!(channel = libssh2_channel_open_session (session)))
62 {
63 fprintf (stderr, "Cannot open channel!\n");
64 return -1;
65 }
66 libssh2_channel_shell (channel);
67
68 // Run a command
69 libssh2_channel_write (channel, cmd, strlen (cmd));
70
71 // Close terminal
72 libssh2_channel_close (channel);
73 libssh2_channel_free (channel);
74
75 // Disconnect
76 libssh2_session_disconnect (session, "Goodbye");
77 libssh2_session_free (session);
78
79 printf ("All done.\n");
80
81 return 0;
82 }
Download | Top | Back | Home
Maintained by Pioz