Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <iostream>
- using namespace std;
- #include <libssh/libsshpp.hpp>
- #include <libssh/libssh.h>
- int main(int argc, const char **argv)
- {
- ssh::Session session;
- int port = 22;
- int verbosity = SSH_LOG_NOLOG; //SSH_LOG_PROTOCOL
- string host = "localhost";
- string user = "user";
- string password = "password";
- //Set options
- session.setOption(SSH_OPTIONS_PORT, &port);
- session.setOption(SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
- session.setOption(SSH_OPTIONS_HOST, host.c_str());
- session.setOption(SSH_OPTIONS_USER, user.c_str());
- /* Attempt to connect to host. On failure, catch SshException and print
- * error message. */
- cout << "Connecting..." << flush;
- try
- {
- session.connect();
- cout << "Connected." << endl;
- //Perform host-key checking
- cout << "Checking host keys..." << flush;
- int host_key_status = session.isServerKnown();
- switch(host_key_status)
- {
- case SSH_SERVER_KNOWN_OK:
- cout << "valid." << endl;
- break;
- case SSH_SERVER_KNOWN_CHANGED:
- case SSH_SERVER_FOUND_OTHER:
- cout << endl << "Something strange is going on with the server's"
- "host key. Unless you know what is causing this,"
- "you may be the target of an attack." << endl;
- exit(1);
- break;
- case SSH_SERVER_NOT_KNOWN:
- case SSH_SERVER_FILE_NOT_FOUND:
- //There is currently no way to get the host key fingerprint/hash through
- //the CPP bindings for libssh. If there were, we would present them to the
- //user to verify that they are connecting to the correct server.
- cout << "Connecting to an unknown server." << endl;
- break;
- case SSH_SERVER_ERROR:
- cout << "Error while checking host keys." << endl;
- exit(1);
- break;
- }
- //Password authentication after connection
- cout << "Authenticating..." << flush;
- int auth_status = session.userauthPassword(password.c_str());
- switch(auth_status)
- {
- case SSH_AUTH_SUCCESS:
- cout << "done." << endl;
- break;
- case SSH_AUTH_PARTIAL:
- case SSH_AUTH_DENIED:
- cout << "failed." << endl;
- exit(1);
- break;
- default:
- cout << "unknown error." << endl;
- exit(1);
- break;
- }
- cout << "Opening channel..." << flush;
- ssh::Channel channel(session);
- cout << "done." << endl;
- cout << "Opening session..." << flush;
- channel.openSession();
- cout << "done." << endl;
- //Do something
- channel.requestExec( "ps aux" );
- sleep(1);
- int recv_buf[512];
- int nbytes = channel.read(recv_buf, sizeof(recv_buf), 10);
- while(nbytes > 0)
- {
- if(fwrite(recv_buf, 1, nbytes, stdout) != nbytes)
- {
- cerr << "error reading" << endl;
- }
- nbytes = channel.read(recv_buf, sizeof(recv_buf), 10);
- }
- //Close channel
- channel.close();
- channel.sendEof();
- //Disconnect
- session.disconnect();
- cout << "Done." << endl;
- }
- catch(ssh::SshException e)
- {
- cout << e.getError() << endl;
- exit(1);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement