Bash脚本与期望。将参数设置为多个测试板

问题描述 投票:1回答:1

我正在为学校做一个小项目。我正在使用15个左右的调谐器来模拟Cell网络。我还没精通脚本编写。我是一个EE,通常谷歌搜索,直到我有一些能满足我目的的frankencode。

目标是快速设置所有模块,因此我想用脚本自动化该过程。这需要ssh,到目前为止我每次都必须手动输入密码。今天早上我用Expect和sshpass建立了一个基本测试。在任何一种情况下,我都可以正确登录,但不能向远程机器发出指令。

我正在读sshpass发送远程指令有困难,如果我错了就纠正我。

/usr/bin/expect << EOF
spawn ssh root@<IP>
expect "(yes/no)?" #Are you sure you want to connect nonsense
send "yes\r"
expect "password"
send "$pass\r"

我在这里试了几件让设备接收指令

interact
cat /pathto/config.txt
#or
send "cat /pathto/config.txt
#the real goal is to send this instruction
sqlite3 /database.db "update table set param=X"


EOF
bash sqlite expect sshpass
1个回答
0
投票

您也可以将其作为expect脚本,而不是shell脚本

#!/usr/bin/expect -f

然后将IP地址作为命令行参数传递给脚本

expect myloginscript.exp 128.0.0.1 the_password

在expect脚本中,您将从参数列表中获取该IP地址

set ip [lindex $argv 0]
set pass [lindex $argv 1]

(将密码放在命令行上并不是一种很好的安全措施。您可以研究将密码传递给期望脚本的更好方法。)

要使用ssh,只有第一次连接才会被问到“你确定”,所以让我们有条件。这是通过让expect命令等待几种模式来完成的:

spawn ssh root@$ip
expect {
    "(yes/no)?" {
        send "yes\r"
        # continue to wait for the password prompt
        exp_continue
    }
    "password" {
        send "$pass\r"
    }
}

一旦发送,您应该期望看到您的shell提示。这种模式取决于您自己的配置,但通常以散列和空格结束。

expect -re {# $}

现在您可以自动执行其余命令:

send "cat /pathto/config.txt\r"
expect -re {# $}

# note the quoting
send "sqlite3 /database.db \"update table set param='X'\"\r"
expect -re {# $}

此时,您需要注销:

send "exit\r"
expect eof

另一方面,如果您设置了ssh私钥认证(请参阅ssh-keygenssh-copy-id),您可以这样做:

ssh root@IP sqlite3 /database.db "update table set param='$X'"

并且根本不需要期待。

© www.soinside.com 2019 - 2024. All rights reserved.