NVIDIA Jetson working

利用spawn和expect自动交互并返回交互结果

2020-03-06  本文已影响0人  童年雅趣

如下脚本实现了如何利用expect和spawn实现主机间相互访问并获取结果(成功返回0,失败返回1),例如:每次ssh远程登录时都需要输入密码,而通过脚本1就可以实现不用输入密码自动登陆。

1、远程Host ssh 登陆脚本(ssh)

#!/bin/bash
#./expect_ssh.sh  hostIP loginName Password
./expect_ssh.sh  192.168.1.168 ubuntu 123456
#!/usr/bin/expect
#expect_ssh.sh

set host [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]

spawn ssh $username@$host 
expect {
        "(yes/no)" { send "yes\r"; exp_continue }
        "password:" { send "$password\r" }
}
interact

2、远程Host scp拷贝文件脚本(并返回拷贝是否成功结果)

#!/bin/bash
#./expect_scp.sh  hostIP loginName Password  Src_file Dest_file
./expect_scp.sh  192.168.1.168 ubuntu 123456  $src_file $dest_file
var=$?
echo $var

if [ $var -eq 0 ]; then
    echo "expect_scp copy file success"
else
    echo "expect_scp copy file failed"
fi
#!/usr/bin/expect
#./expect_scp.sh 


set timeout 10
set host [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set src_file [lindex $argv 3]
set dest_file [lindex $argv 4]
spawn scp $src_file $username@$host:$dest_file
expect {
    "(yes/no)?"
    {
    send "yes\n"
    expect "*assword:" { send "$password\n"}
    }
    "*assword:"
    {
    send "$password\n"
    }
}

expect "100%"
expect eof

catch wait result
exit [lindex $result 3]
上一篇下一篇

猜你喜欢

热点阅读