Ssh return error code

A typical SSH session A SSH session goes through the following steps: Before connecting to the server, you can set up if you wish one or other server public key authentication, i.e. DSA or RSA. You can choose cryptographic algorithms you trust and compression algorithms if any. You must of course set up the […]

Содержание

  1. A typical SSH session
  2. Creating the session and setting options
  3. A typical SSH session
  4. Creating the session and setting options
  5. SSH return code status and error handling
  6. 3 Answers 3
  7. Can I get the exit code of a command executed in a subshell via ssh?
  8. 2 Answers 2
  9. ssh script returns 255 error
  10. 8 Answers 8

A typical SSH session

A SSH session goes through the following steps:

  • Before connecting to the server, you can set up if you wish one or other server public key authentication, i.e. DSA or RSA. You can choose cryptographic algorithms you trust and compression algorithms if any. You must of course set up the hostname.
  • The connection is established. A secure handshake is made, and resulting from it, a public key from the server is gained. You MUST verify that the public key is legitimate, using for instance the MD5 fingerprint or the known hosts file.
  • The client must authenticate: the classical ways are password, or public keys (from dsa and rsa key-pairs generated by openssh). If a SSH agent is running, it is possible to use it.
  • Now that the user has been authenticated, you must open one or several channels. Channels are different subways for information into a single ssh connection. Each channel has a standard stream (stdout) and an error stream (stderr). You can theoretically open an infinity of channels.
  • With the channel you opened, you can do several things:
    • Execute a single command.
    • Open a shell. You may want to request a pseudo-terminal before.
    • Invoke the sftp subsystem to transfer files.
    • Invoke the scp subsystem to transfer files.
    • Invoke your own subsystem. This is outside the scope of this document, but can be done.
  • When everything is finished, just close the channels, and then the connection.

The sftp and scp subsystems use channels, but libssh hides them to the programmer. If you want to use those subsystems, instead of a channel, you’ll usually open a «sftp session» or a «scp session».

Creating the session and setting options

The most important object in a SSH connection is the SSH session. In order to allocate a new SSH session, you use ssh_new(). Don’t forget to always verify that the allocation succeeded.

libssh follows the allocate-it-deallocate-it pattern. Each object that you allocate using xxxxx_new() must be deallocated using xxxxx_free(). In this case, ssh_new() does the allocation and ssh_free() does the contrary.

The ssh_options_set() function sets the options of the session. The most important options are:

  • SSH_OPTIONS_HOST: the name of the host you want to connect to
  • SSH_OPTIONS_PORT: the used port (default is port 22)
  • SSH_OPTIONS_USER: the system user under which you want to connect
  • SSH_OPTIONS_LOG_VERBOSITY: the quantity of messages that are printed

The complete list of options can be found in the documentation of ssh_options_set(). The only mandatory option is SSH_OPTIONS_HOST. If you don’t use SSH_OPTIONS_USER, the local username of your account will be used.

Источник

A typical SSH session

A SSH session goes through the following steps:

  • Before connecting to the server, you can set up if you wish one or other server public key authentication, i.e. DSA or RSA. You can choose cryptographic algorithms you trust and compression algorithms if any. You must of course set up the hostname.
  • The connection is established. A secure handshake is made, and resulting from it, a public key from the server is gained. You MUST verify that the public key is legitimate, using for instance the MD5 fingerprint or the known hosts file.
  • The client must authenticate: the classical ways are password, or public keys (from dsa and rsa key-pairs generated by openssh). If a SSH agent is running, it is possible to use it.
  • Now that the user has been authenticated, you must open one or several channels. Channels are different subways for information into a single ssh connection. Each channel has a standard stream (stdout) and an error stream (stderr). You can theoretically open an infinity of channels.
  • With the channel you opened, you can do several things:
    • Execute a single command.
    • Open a shell. You may want to request a pseudo-terminal before.
    • Invoke the sftp subsystem to transfer files.
    • Invoke the scp subsystem to transfer files.
    • Invoke your own subsystem. This is outside the scope of this document, but can be done.
  • When everything is finished, just close the channels, and then the connection.

The sftp and scp subsystems use channels, but libssh hides them to the programmer. If you want to use those subsystems, instead of a channel, you’ll usually open a «sftp session» or a «scp session».

Creating the session and setting options

The most important object in a SSH connection is the SSH session. In order to allocate a new SSH session, you use ssh_new(). Don’t forget to always verify that the allocation succeeded.

libssh follows the allocate-it-deallocate-it pattern. Each object that you allocate using xxxxx_new() must be deallocated using xxxxx_free(). In this case, ssh_new() does the allocation and ssh_free() does the contrary.

The ssh_options_set() function sets the options of the session. The most important options are:

  • SSH_OPTIONS_HOST: the name of the host you want to connect to
  • SSH_OPTIONS_PORT: the used port (default is port 22)
  • SSH_OPTIONS_USER: the system user under which you want to connect
  • SSH_OPTIONS_LOG_VERBOSITY: the quantity of messages that are printed

The complete list of options can be found in the documentation of ssh_options_set(). The only mandatory option is SSH_OPTIONS_HOST. If you don’t use SSH_OPTIONS_USER, the local username of your account will be used.

Источник

SSH return code status and error handling

I want to check if files count is 0 on Remote server using ssh.

Below code is only checking if file (ending with .dmp exists )

For below «then» part is executed with $? =0 when actual error «ls: cannot access /apps/oracle/home/DB_1201/*.dmp: No such file or directory»

I need output of «ls /apps/oracle/home/DB_1201/*.dmp |wc -l» 0 or N number. And if directory is not there (No such file or directory).

Need to return file count 0 or 28 and/or capture directory not found error.

Please advise on the correct approach of executing the SCP and after that validating its status?

Below always returns zero even if some error as its taking local server last command status.

3 Answers 3

if [ `ssh v0021x91 ls /apps/oracle/home/DB_1201/*.dmp | wc -l` -eq 0 ]

The evaluation order is such that the wildcard is evaluated before the ssh command is executed. If /apps/oracle/home/DB_1202/*.dmp matches one or more files on the local host, it will be replaced with the name(s) of those file(s). Otherwise, the asterisk will remain and be passed to the remote side as literal.

The remote shell will then evaluate the pattern before executing the ls command, either expanding it to one or more matching files or leaving it as a literal asterisk.

If there are no matching files, ls will complain with an error that it cannot find the file /apps/oracle/home/DB_1201/*.dmp (complete with a literal asterisk as the first character of the file name). As a side effect it will output no files to wc -l and you’ll get zero as the expected and correct result there.

Finally, the test will match either zero files along with an error written to stderr, or some non-zero number of files.

As a point of modern coding, consider replacing [ `command` ] with [ «$(command)» ] . Or, if you’re writing for bash , [[ «$(command)» ]]

Exit codes should either be 0 (success, ok) or in the range 1-127. Using large or negative numbers is erroneous and misleading

You’re using a string comparison for numeric values. In practical terms it’s probably ok, but you should use [ $? -ne 0 ] or [ $? -gt 0 ] instead.

if scp -rp /apps/oracle/home/DB_1201/*dmp oracle @ v0021x91:/apps/oracle/home/DB_1201/*dmp

  • What’s with the spaces in the target component?
  • Don’t specify wildcards in the target unless you really really know what you’re doing

It should almost certainly be oracle@v0021x91:/apps/oracle/home/dB_1202/

if ssh v0021x91 ls /apps/oracle/home/DB_1201/*.dmp

Similar to #1, you’ll get an error if there are no files matching *.dmp on the remote machine, and unexpected problems if there are one or more files matching that path on the local machine.

To avoid expansion of wildcards on the local system, quote the command you’re passing to ssh . So for #5 you should write if ssh v0021x91 ‘ls /apps/oracle/home/DB_1201/*.dmp’ , etc.

Источник

Can I get the exit code of a command executed in a subshell via ssh?

I’m trying to use Paramiko to write a deployment script, and I’m having trouble with exit codes from the commands I run. I’m using code similar to that in this answer, but it’s a little more complicated. Basically, from our dev boxes we have to go through a jump server, and from there to a series of production machines. Once there we have to switch to a system user (sudo su — systemuser) and then we can run commands.

The problem is that as I understand it I have 3 subshells — the ssh session, the nested ssh command and then the su subshell. I can’t get Paramiko to give me back the exit code of the commands in the inner subshell — I guess the exit code it will eventually return will be that of the ssh command. I suspect this problem is not actually specific to Paramiko — does the SSH protocol even support this kind of usage?

I’m currently always executing:

and then parsing this out on the client, but it’s pretty ugly — is there a nicer way?

2 Answers 2

I guess the exit code it will eventually return will be that of the ssh command. I suspect this problem is not actually specific to Paramiko — does the SSH protocol even support this kind of usage?

The exit status is always returned, but it may not be from where you think. Once you call invoke_shell() , your remote process is a shell, probably bash. The exit_status you receive will be the one from that shell, not any of the processes it ran. Paramiko (nor any ssh implementation) can ever return the exit status of your commands, because the exit statuses are never seen outside of that remote shell. It’s up to you to determine what your exit status should be, and exit the shell with exit $EXIT_STATUS (often exit $? is enough)

If you can break up your commands, or wrap them in a script, then use the exec_command() method, you will have access to the correct exit status directly.

Alternatively, you can use shell command exec in the remote shell, and the shell’s process will be replaced by the command called by exec, and its exit status will be returned.

Источник

ssh script returns 255 error

In my code I have the following to run a remote script.

For some reason it keeps 255’ing on me. Any ideas?

I can SSH into the box just fine (passless keys setup)

8 Answers 8

This is usually happens when the remote is down/unavailable; or the remote machine doesn’t have ssh installed; or a firewall doesn’t allow a connection to be established to the remote host.

ssh returns 255 when an error occurred or 255 is returned by the remote script:

Usually you would an error message something similar to:

Check-list:

What happens if you run the ssh command directly from the command line?

Are you able to ping that machine?

Does the remote has ssh installed?

If installed, then is the ssh service running?

This error will also occur when using pdsh to hosts which are not contained in your «known_hosts» file.

I was able to correct this by SSH’ing into each host manually and accepting the question «Do you want to add this to known hosts».

If there’s a problem with authentication or connection, such as not being able to read a password from the terminal, ssh will exit with 255 without being able to run your actual script. Verify to make sure you can run ‘true’ instead, to see if the ssh connection is established successfully.

Isn’t the problem in the lines:

Correct me if I’m wrong but I believe exit 999 is out of range for an exit code and results in a exit status of 255.

I was stumped by this. Once I got passed the 255 problem. I ended up with a mysterious error code 1. This is the foo to get that resolved:

-P means write the output out as you go and is optional. But the -x ‘-tt’ trick is what forces a psuedo tty to be allocated.

You can get a clue what the error code 1 means this if you try:

Notice the return code for this is 1, which is what pssh is reporting to you.

I found this -x -tt trick here. Also note that turning on verbose mode (pssh —verbose) for these cases does nothing to help you.

Источник

  • Document ID:7021696
  • Creation Date:07-Dec-2006
  • Modified Date:26-Mar-2018
    • Micro Focus Products:

      Reflection (legacy 14.1)

Environment

Reflection for HP version 13.0.4 through 14.0.3

Reflection for UNIX and OpenVMS version 13.0.4 through 14.0.3

Reflection for ReGIS Graphics version 13.0.4 through 14.0.3

Situation

This technical note lists the return codes for SSH and SCP.

Note: For a list of SSH or SCP return codes that apply to later Reflection versions, see KB 7021996.

For return codes that apply to the UNIX Client, see KB 7021956.

Resolution

To display the return code: Use echo %errorlevel% to display the return code after executing an SSH or SCP command.

SSH Return Codes

0 Operation was successful
1 Generic error, usually because invalid command line options or malformed configuration
2 Connection failed
65 Host not allowed to connect
66 General error in ssh protocol
67 Key exchange failed
68 Reserved
69 MAC error
70 Compression error
71 Service not available
72 Protocol version not supported
73 Host key not verifiable
74 Connection failed
75 Disconnected by application
76 Too many connections
77 Authentication cancelled by user
78 No more authentication methods available
79 Invalid user name

SCP Return Codes

0 Operation was successful
1 General error in file copy
2 Destination is not directory, but it should be
3 Maximum symlink level exceeded
4 Connecting to host failed.
5 Connection broken
6 File does not exist
7 No permission to access file.
8 General error in sftp protocol
9 File transfer protocol mismatch
10 No file matches a given criteria
65 Host not allowed to connect
66 General error in ssh protocol
67 Key exchange failed
68 Reserved
69 MAC error
70 Compression error
71 Service not available
72 Protocol version not supported
73 Host key not verifiable
74 Connection failed
75 Disconnected by application
76 Too many connections
77 Authentication cancelled by user
78 No more authentication methods available
79 Invalid user name

Additional Information

Legacy KB ID

This document was originally published as Attachmate Technical Note 2116.

© Micro Focus.
Please see Terms of Use applicable to this content.

Chapter 1: A typical SSH session

A SSH session goes through the following steps:

  • Before connecting to the server, you can set up if you wish one or other server public key authentication, i.e. DSA or RSA. You can choose cryptographic algorithms you trust and compression algorithms if any. You must of course set up the hostname.
  • The connection is established. A secure handshake is made, and resulting from it, a public key from the server is gained. You MUST verify that the public key is legitimate, using for instance the MD5 fingerprint or the known hosts file.
  • The client must authenticate: the classical ways are password, or public keys (from dsa and rsa key-pairs generated by openssh). If a SSH agent is running, it is possible to use it.
  • Now that the user has been authenticated, you must open one or several channels. Channels are different subways for information into a single ssh connection. Each channel has a standard stream (stdout) and an error stream (stderr). You can theoretically open an infinity of channels.
  • With the channel you opened, you can do several things:
    • Execute a single command.
    • Open a shell. You may want to request a pseudo-terminal before.
    • Invoke the sftp subsystem to transfer files.
    • Invoke the scp subsystem to transfer files.
    • Invoke your own subsystem. This is outside the scope of this document, but can be done.
  • When everything is finished, just close the channels, and then the connection.

The sftp and scp subsystems use channels, but libssh hides them to the programmer. If you want to use those subsystems, instead of a channel, you’ll usually open a “sftp session” or a “scp session”.

Creating the session and setting options

The most important object in a SSH connection is the SSH session. In order to allocate a new SSH session, you use ssh_new(). Don’t forget to always verify that the allocation successed.

#include <libssh/libssh.h>
#include <stdlib.h>

int main()
{
  ssh_session my_ssh_session = ssh_new();
  if (my_ssh_session == NULL)
    exit(-1);
  ...
  ssh_free(my_ssh_session);
}

libssh follows the allocate-it-deallocate-it pattern. Each object that you allocate using xxxxx_new() must be deallocated using xxxxx_free(). In this case, ssh_new() does the allocation and ssh_free() does the contrary.

The ssh_options_set() function sets the options of the session. The most important options are:

  • SSH_OPTIONS_HOST: the name of the host you want to connect to
  • SSH_OPTIONS_PORT: the used port (default is port 22)
  • SSH_OPTIONS_USER: the system user under which you want to connect
  • SSH_OPTIONS_LOG_VERBOSITY: the quantity of messages that are printed

The complete list of options can be found in the documentation of ssh_options_set(). The only mandatory option is SSH_OPTIONS_HOST. If you don’t use SSH_OPTIONS_USER, the local username of your account will be used.

Here is a small example of how to use it:

#include <libssh/libssh.h>
#include <stdlib.h>

int main()
{
  ssh_session my_ssh_session;
  int verbosity = SSH_LOG_PROTOCOL;
  int port = 22;

  my_ssh_session = ssh_new();
  if (my_ssh_session == NULL)
    exit(-1);

  ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");
  ssh_options_set(my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
  ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port);

  ...

  ssh_free(my_ssh_session);
}

Please notice that all parameters are passed to ssh_options_set() as pointers, even if you need to set an integer value.

Connecting to the server

Once all settings have been made, you can connect using ssh_connect(). That function will return SSH_OK if the connection worked, SSH_ERROR otherwise.

You can get the English error string with ssh_get_error() in order to show the user what went wrong. Then, use ssh_disconnect() when you want to stop the session.

Here’s an example:

#include <libssh/libssh.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
  ssh_session my_ssh_session;
  int rc;

  my_ssh_session = ssh_new();
  if (my_ssh_session == NULL)
    exit(-1);

  ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");

  rc = ssh_connect(my_ssh_session);
  if (rc != SSH_OK)
  {
    fprintf(stderr, "Error connecting to localhost: %sn",
            ssh_get_error(my_ssh_session));
    exit(-1);
  }

  ...

  ssh_disconnect(my_ssh_session);
  ssh_free(my_ssh_session);
}

Authenticating the server

Once you’re connected, the following step is mandatory: you must check that the server you just connected to is known and safe to use (remember, SSH is about security and authentication).

There are two ways of doing this:

  • The first way (recommended) is to use the ssh_is_server_known() function. This function will look into the known host file (~/.ssh/known_hosts on UNIX), look for the server hostname’s pattern, and determine whether this host is present or not in the list.
  • The second way is to use ssh_get_pubkey_hash() to get a binary version of the public key hash value. You can then use your own database to check if this public key is known and secure.

You can also use the ssh_get_pubkey_hash() to show the public key hash value to the user, in case he knows what the public key hash value is (some paranoid people write their public key hash values on paper before going abroad, just in case …).

If the remote host is being used to for the first time, you can ask the user whether he/she trusts it. Once he/she concluded that the host is valid and worth being added in the known hosts file, you use ssh_write_knownhost() to register it in the known hosts file, or any other way if you use your own database.

The following example is part of the examples suite available in the examples/ directory:

#include <errno.h>
#include <string.h>

int verify_knownhost(ssh_session session)
{
  int state, hlen;
  unsigned char *hash = NULL;
  char *hexa;
  char buf[10];

  state = ssh_is_server_known(session);

  hlen = ssh_get_pubkey_hash(session, &hash);
  if (hlen < 0)
    return -1;

  switch (state)
  {
    case SSH_SERVER_KNOWN_OK:
      break; /* ok */

    case SSH_SERVER_KNOWN_CHANGED:
      fprintf(stderr, "Host key for server changed: it is now:n");
      ssh_print_hexa("Public key hash", hash, hlen);
      fprintf(stderr, "For security reasons, connection will be stoppedn");
      free(hash);
      return -1;

    case SSH_SERVER_FOUND_OTHER:
      fprintf(stderr, "The host key for this server was not found but an other"
        "type of key exists.n");
      fprintf(stderr, "An attacker might change the default server key to"
        "confuse your client into thinking the key does not existn");
      free(hash);
      return -1;

    case SSH_SERVER_FILE_NOT_FOUND:
      fprintf(stderr, "Could not find known host file.n");
      fprintf(stderr, "If you accept the host key here, the file will be"
       "automatically created.n");
      /* fallback to SSH_SERVER_NOT_KNOWN behavior */

    case SSH_SERVER_NOT_KNOWN:
      hexa = ssh_get_hexa(hash, hlen);
      fprintf(stderr,"The server is unknown. Do you trust the host key?n");
      fprintf(stderr, "Public key hash: %sn", hexa);
      free(hexa);
      if (fgets(buf, sizeof(buf), stdin) == NULL)
      {
        free(hash);
        return -1;
      }
      if (strncasecmp(buf, "yes", 3) != 0)
      {
        free(hash);
        return -1;
      }
      if (ssh_write_knownhost(session) < 0)
      {
        fprintf(stderr, "Error %sn", strerror(errno));
        free(hash);
        return -1;
      }
      break;

    case SSH_SERVER_ERROR:
      fprintf(stderr, "Error %s", ssh_get_error(session));
      free(hash);
      return -1;
  }

  free(hash);
  return 0;
}

Authenticating the user

The authentication process is the way a service provider can identify a user and verify his/her identity. The authorization process is about enabling the authenticated user the access to ressources. In SSH, the two concepts are linked. After authentication, the server can grant the user access to several ressources such as port forwarding, shell, sftp subsystem, and so on.

libssh supports several methods of authentication:

  • “none” method. This method allows to get the available authentications methods. It also gives the server a chance to authenticate the user with just his/her login. Some very old hardware uses this feature to fallback the user on a “telnet over SSH” style of login.
  • password method. A password is sent to the server, which accepts it or not.
  • keyboard-interactive method. The server sends several challenges to the user, who must answer correctly. This makes possible the authentication via a codebook for instance (“give code at 23:R on page 3”).
  • public key method. The host knows the public key of the user, and the user must prove he knows the associated private key. This can be done manually, or delegated to the SSH agent as we’ll see later.

All these methods can be combined. You can for instance force the user to authenticate with at least two of the authentication methods. In that case, one speaks of “Partial authentication”. A partial authentication is a response from authentication functions stating that your credential was accepted, but yet another one is required to get in.

The example below shows an authentication with password:

#include <libssh/libssh.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
  ssh_session my_ssh_session;
  int rc;
  char *password;

  // Open session and set options
  my_ssh_session = ssh_new();
  if (my_ssh_session == NULL)
    exit(-1);
  ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");

  // Connect to server
  rc = ssh_connect(my_ssh_session);
  if (rc != SSH_OK)
  {
    fprintf(stderr, "Error connecting to localhost: %sn",
            ssh_get_error(my_ssh_session));
    ssh_free(my_ssh_session);
    exit(-1);
  }

  // Verify the server's identity
  // For the source code of verify_knowhost(), check previous example
  if (verify_knownhost(my_ssh_session) < 0)
  {
    ssh_disconnect(my_ssh_session);
    ssh_free(my_ssh_session);
    exit(-1);
  }

  // Authenticate ourselves
  password = getpass("Password: ");
  rc = ssh_userauth_password(my_ssh_session, NULL, password);
  if (rc != SSH_AUTH_SUCCESS)
  {
    fprintf(stderr, "Error authenticating with password: %sn",
            ssh_get_error(my_ssh_session));
    ssh_disconnect(my_ssh_session);
    ssh_free(my_ssh_session);
    exit(-1);
  }

  ...

  ssh_disconnect(my_ssh_session);
  ssh_free(my_ssh_session);
}

Doing something

At this point, the authenticity of both server and client is established. Time has come to take advantage of the many possibilities offered by the SSH protocol: execute a remote command, open remote shells, transfer files, forward ports, etc.

The example below shows how to execute a remote command:

int show_remote_processes(ssh_session session)
{
  ssh_channel channel;
  int rc;
  char buffer[256];
  int nbytes;

  channel = ssh_channel_new(session);
  if (channel == NULL)
    return SSH_ERROR;

  rc = ssh_channel_open_session(channel);
  if (rc != SSH_OK)
  {
    ssh_channel_free(channel);
    return rc;
  }

  rc = ssh_channel_request_exec(channel, "ps aux");
  if (rc != SSH_OK)
  {
    ssh_channel_close(channel);
    ssh_channel_free(channel);
    return rc;
  }

  nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
  while (nbytes > 0)
  {
    if (write(1, buffer, nbytes) != (unsigned int) nbytes)
    {
      ssh_channel_close(channel);
      ssh_channel_free(channel);
      return SSH_ERROR;
    }
    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
  }

  if (nbytes < 0)
  {
    ssh_channel_close(channel);
    ssh_channel_free(channel);
    return SSH_ERROR;
  }

  ssh_channel_send_eof(channel);
  ssh_channel_close(channel);
  ssh_channel_free(channel);

  return SSH_OK;
}

Handling the errors

All the libssh functions which return an error value also set an English error message describing the problem.

Error values are typically SSH_ERROR for integer values, or NULL for pointers.

The function ssh_get_error() returns a pointer to the static error message.

ssh_error_code() returns the error code number : SSH_NO_ERROR, SSH_REQUEST_DENIED, SSH_INVALID_REQUEST, SSH_CONNECTION_LOST, SSH_FATAL, or SSH_INVALID_DATA. SSH_REQUEST_DENIED means the ssh server refused your request, but the situation is recoverable. The others mean something happened to the connection (some encryption problems, server problems, …). SSH_INVALID_REQUEST means the library got some garbage from server, but might be recoverable. SSH_FATAL means the connection has an important problem and isn’t probably recoverable.

Most of time, the error returned are SSH_FATAL, but some functions (generaly the ssh_request_xxx ones) may fail because of server denying request. In these cases, SSH_REQUEST_DENIED is returned.

For thread safety, errors are bound to ssh_session objects. As long as your ssh_session object is not NULL, you can retrieve the last error message and error code from the ssh_session using ssh_get_error() and ssh_get_error_code() respectively.

The SFTP subsystem has its own error codes, in addition to libssh ones.

See also:

ssh_new

ssh_free

ssh_options_set

ssh_options_parse_config

ssh_options_copy

ssh_options_getopt

ssh_connect

ssh_disconnect

ssh_get_error

ssh_get_error_code

ssh_get_pubkey_hash

ssh_is_server_known

ssh_write_knownhost

A deeper insight on authentication

Opening a remote shell

Passing a remote command

The SFTP subsystem

The SCP subsystem

#!/bin/bash # # SSH Exit Codes # # Using SSH in scripting is pretty standard, but sometimes you want to stop execution of a script # if a command inside an SSH session fails to exit cleanly (return 0). The key to remember is that # the ssh command’s exit code will be that of the *last executed* command inside the ssh session, just # like a bash script ends with the exit code of the last command executed unless you specifically # call exit. # # See the examples below for various ways of handling ssh connections running multiple commands # and how that interacts with it’s exit value and the usage of «set -e» in the shell. REMOTE_SERVER=«insert-test-server-here.example.org« echo «Testing exit codes from HEREDOC ssh connections with a set -e« ssh $REMOTE_SERVER << EOF set -e someNonExistantCommand hostname EOF echo «Return of SSH Connection: $?« # This version returns non-zero because of failed command, and never runs hostname # The set -e allows this to happen. ############################################################################### echo echo «Testing exit codes from HEREDOC ssh connections without a set -e« ssh $REMOTE_SERVER << EOF someNonExistantCommand hostname EOF echo «Return of SSH Connection: $?« # This returns zero and runs hostname # Without the set -e designated in the ssh shell’s environment, all commands # will happily run. Since hostname shouldn’t fail, it will return a 0 ############################################################################### echo echo «Testing exit codes from ssh connections with a set -e using quotations and semicolons« ssh $REMOTE_SERVER « set -e ; someNonExistantCommand ; hostname « echo «Return of SSH Connection: $?« # This version returns non-zero because of failed command, and never runs hostname # The set -e stops execution at the bad command. ############################################################################### echo echo «Testing exit codes from ssh connections without a set -e using quotations and semicolons« ssh $REMOTE_SERVER « someNonExistantCommand ; hostname « echo «Return of SSH Connection: $?« # This returns zero and runs hostname # Similar to the HEREDOC version, the shell continues to run commands after a failed one. # The semicolon doesn’t stop additional execution from happening. ############################################################################### echo echo «Testing exit codes from ssh connections with a set -e using quotations and ampersands« ssh $REMOTE_SERVER « set -e && someNonExistantCommand && hostname « echo «Return of SSH Connection: $?« # This version returns non-zero because of failed command, and never runs hostname # Again, the set -e here stops our execution before ever running hostname. ############################################################################### echo echo «Testing exit codes from ssh connections without a set -e using quotations and ampersands« ssh $REMOTE_SERVER « someNonExistantCommand && hostname « echo «Return of SSH Connection: $?« # This version returns non-zero because of failed command, and never runs hostname # Here, it’s actually the && that stops our execution. This boolean operator will # only continue if the previous command executes cleanly, so when the bad command # exits with a non-zero return code, it stops execution and hostname never runs.

Понравилась статья? Поделить с друзьями:
  • Ssh host key verification failed как исправить
  • Ssh exited with error status 255 restarting ssh
  • Ssh error publickey permission denied
  • Ssh error no such target
  • Ssh error no display environment variable specified