Last Updated: February 25, 2016
·
15.59K
· christurnbull

Run SU with password command line argument

sudo has the option -S that lets you supply a password via command line argument.

su does not. The script below uses expect to supply input to su by passing stdin through a tty.

#!/usr/bin/expect -f
#Usage: script.sh cmd user pass

set cmd [lindex $argv 0];
set user [lindex $argv 1];
set pass [lindex $argv 2];

log_user 0
spawn su -c $cmd - $user
expect "Password: "
log_user 1
send "$pass\r"
expect "$ "

Run the script with

./runas.sh "ls -l" bob 1234