This topic describes how to verify whether you have the permission to use sudo commands when you use a Java SSH tool, for example, JsCh, to connect to a remote host. During Linux interactions, the Java client hangs, resulting in thread blocking. Therefore, the key is to skip the password entry interaction after you run a sudo command.
Background
The following two authorization methods are available for logging on to a host by using an SSH tool:
Authorization with the username and password. You can use the username and password to log on by using 'ssh xxx@xx.xx.xx.xx.
Authorization with the private key. You can use a private key on a client to log on to a host, provided that the public key that is paired with the private key exists in the authorized_keys file of the host. This is a password-free logon.
Logon with a username
To verify whether a user that has logged on by using ssh root@password has sudo permissions, run the following command:
echo password |sudo -S ls
Three different results may be returned in the following three cases.
- The user has sudo permissions.
- The user does not have sudo permissions. In this case, the command returns the following information: `[sudo] password for xxx: xxx is not in the sudoers file. This incident will be reported.`
Logon with a private key
During logon with a private key or password-free logon, the Java client does not know the password of the user. The host must be configured to allow the user to run sudo commands without a password. That is, the following line exists in the /etc/sudoers file:
username ALL=(ALL) NOPASSWD:ALL
The above configuration specifies that the specified username can execute any commands without password.
Therefore, before verifying whether a user has sudo permissions, you must run the following command to determine whether the user can run sudo commands without entering a password:
sudo -n true
If no result is returned for the above command, the user is allowed to run sudo commands without a password and has sudo permissions.
If sudo: a password is required is returned, the user must enter a password to run sudo commands.
Verify the result
echo password |sudo -S ls >/dev/null 2>&1; echo $?
If 0 is returned, the execution succeeds and the user has sudo permissions. If 1 is returned, the execution fails and the user does not have sudo permissions.
sudo -n true >/dev/null 2>&1; echo $?
If 1 is returned, the host is configured to allow the user run sudo commands without a password. If 0 is returned, the host is not configured to allow the user run sudo commands without a password.