2016-04-14 102 views
2

我需要创建一个bash脚本来远程运行一批机器上的另一个脚本。为此,我通过SSH传递脚本。使用'expect'命令将密码传递给远程运行脚本的SSH

ssh -p$port [email protected]$ip 'bash -s' < /path/to/script/test.sh 

我认为它会用我的RSA密钥,但我得到的错误:

"Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)" 

我试着用sshpass无济于事。所以我的下一个解决方案是使用expect。我从来没有使用过期望,我很积极,我的语法很不错。

ssh -p$port [email protected]$ip 'bash -s' < /path/to/script/test.sh 
/usr/bin/expect <<EOD 
expect "password" 
send "$spass\n" 
send "\n" 
EOD 

我拥有对所有机器的root权限,任何解决方案都会在代码保留在bash中时执行。请记住,这将通过从父脚本传递的全局变量($ spass,$ ip,$ port等)循环完成。

+1

是您的SSH在每个机器的根的'的.ssh/authorized_keys'文件的公钥呢?我认为在这里拍摄的最好的情况是找出为什么当你尝试使用密钥对进行ssh认证的时候,你会得到这样的结果。 – JNevill

+0

您可以尝试使用'ssh -v {port} root @ {ip}'手动连接,以更好地了解正在发生的事情。 – Mike

+2

解决密钥问题是一个比许多密码提示更好的解决方案。 –

回答

3

你做错了两种手段:

  1. 如果你想expectssh互动,您需要从expect脚本,而不是之前启动ssh

  2. 如果你把脚本(/path/to/script/test.sh)到sshstdin,你不能用ssh过程中的任何更多的沟通。

您应该使用scp将脚本复制到远程主机,然后运行它。

Expect脚本可能是这样的:

/usr/bin/expect <<EOF 
spawn ssh -p$port [email protected]$ip 
expect "password" 
send "$Spass\r" 
expect "$ " 
send "/path/to/script/on/remote/server/test.sh\r" 
expect "$ " 
interact 
EOF 
+1

缺少'interact'和'EOF' – dbndhjefj

+0

@szpal谢谢。现在修复。 – Jakuje

+0

谢谢,那当然有诀窍。有没有办法让它等待另一个脚本完成后再继续?我通常使用'source',这会让人期待吗? –

0
#!/usr/bin/expect 
    #Replace with remote username and remote ipaddress 
    spawn /usr/bin/ssh -o StrictHostKeyChecking=no [email protected] 
    #Replace with remote username and remote ipaddress 
    expect "[email protected]'s password: " 
    #Provide remote system password 
    send "urpassword\n" 
    #add commands to be executed. Also possible to execute bash scripts 
    expect "$ " {send "pwd\n"} # bash command 
    expect "$ " {send "cd mytest\n"} 
    expect "$ " {send "./first.sh\n"} # bash scripts 
    expect "$ " {send "exit\n"} 
    interact 
+0

请提供您的答案的描述 –

+0

Expect工具可用于自动交互式应用程序,如ssh,telnet,f​​tp,passwd,fsck,rlogin,提示等。 尝试从以下url中获取一些示例。 http://www.thegeekstuff.com/2010/10/expect-examples –