Using 'expect' command to pass password to SSH running script remotely
You are doing it wrong in two means:
If you want
expect
to interact withssh
, you need to startssh
fromexpect
script and not before.If you put the script (
/path/to/script/test.sh
) tostdin
ofssh
, you can't communicate with thessh
process any more.
You should rather copy the script to remote host using scp and then run it.
Expect script might look like this:
/usr/bin/expect <<EOF
spawn ssh -p$port root@$ip
expect "password"
send "$Spass\r"
expect "$ "
send "/path/to/script/on/remote/server/test.sh\r"
expect "$ "
interact
EOF
Acrid_Soul
Updated on August 21, 2022Comments
-
Acrid_Soul over 1 year
I need to create a bash script that will remotely run another script on a batch of machines. To do so I am passing a script through SSH.
ssh -p$port root@$ip 'bash -s' < /path/to/script/test.sh
I thought it would use my RSA keys but I am getting error:
"Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)"
I tried using sshpass to no avail. So my next solution was using expect. I have never used expect before and I'm positive my syntax is way off.
ssh -p$port root@$ip 'bash -s' < /path/to/script/test.sh /usr/bin/expect <<EOD expect "password" send "$spass\n" send "\n" EOD
I have root access to all machines and ANY solution will do as long as the code remains within bash. Just keep in mind that this will be done in a loop with global variables ($spass, $ip, $port, etc) passed from a parent script.
-
szpal about 8 yearsmissing
interact
andEOF
-
Jakuje about 8 years@szpal Thanks. Fixed now.
-
Acrid_Soul about 8 yearsThanks, that certainly did the trick. Is there a way to make it wait for the other script to finish before it moves on? I usually use
source
, will that play nice with expect? -
Jakuje about 8 yearsI have no idea what you mean. I would consult with manual page, understand what this code snippet do and then try to compose another question, if there will be something unclear.
-
Saurabh Bhandari almost 7 yearsPlease provide description of your answer
-
Admin almost 7 yearsExpect tool can be used for automating interactive applications such as ssh,telnet, ftp, passwd, fsck, rlogin, tip, etc. Try some examples from below url. thegeekstuff.com/2010/10/expect-examples