Sudo cmd via ssh waiting twice in a row

I used expect to execute some command with sudo on the remote host via ssh. The script is as follows:

 spawn ssh -q ${user}@${host} expect "*?assword:" send "${pass}\r" expect "${user}@" send "sudo ls\r" expect "*?assword:" send "${pass}\r" expect "${user}@" send "exit\r" interac 

It works fine for the first time, but when I executed it sequentially, an error occurred. This is because sudo will not expire immediately, therefore, if sudo some command twice in a short time, the second one may not need a password, so the second send "${pass}\r" in the above script failed!

So, how can we detect this and avoid sending a password when sudo does not expire? thanks!

+4
source share
2 answers

Modify the script so that the pending sudo password is optional:

 send "sudo ls\r" expect { "*?assword:" { send "$pass\r" exp_continue } " $user@ " { send "exit\r" } } interac 
+4
source

Clear the sudo authentication cache with sudo -k immediately after logging.

+2
source

Source: https://habr.com/ru/post/1379425/


All Articles