希望SSH无密码
我有一个文件,有IP地址,文件和密码的位置。我无法使用ssh密钥验证,这就是为什么我仅限于在bash脚本中使用expect。该文件包含的信息如下,用空格分隔:希望SSH无密码
IP位置密码
IP位置密码
等
我的脚本是:
VAR=$(expect -c "
set fid [open "file.conf" w]
set content [read $fid]
close $fid
set records [split $content "\n"]
foreach rec $records {
set fields [split $rec]
lassign $fields\ ip location password
puts "$ip"
puts "$location"
puts "$password"}
spawn ssh $ip tail -f $location > /home/log_$ip 2>/dev/null &
expect {
".*Are.*.*yes.*no.*" { send "yes\n" }
"*?assword:*" { send "$password\r" }
}
")
回声“$ VAR “
当我运行脚本时,它给我是错误:
错误#参数:应该是“读取channelId?numChars?”或在执行 “读?-nonewline?渠道ID” “读” 从 中调用“设置内容[阅读]”
您需要封闭预期体在单引号,所以预计不会扩展变量在期望开始执行之前由shell执行。另外,如果您点击“是...是...否”提示,那么您需要使用exp_continue
,以便您可以继续期待密码提示。
请勿使用“w”打开配置文件 - 您将销毁文件内容。你是从中读取,所以打开阅读
VAR=$(expect -c '
set fid [open "file.conf" r]
while {[gets $fid line] != -1} {
lassign [split $line] ip location password
puts "$ip"
puts "$location"
puts "$password"
spawn ssh $ip tail -n 20 $location > /home/log_$ip 2>/dev/null &
expect {
-re "Are.*yes.*no" { send "yes\r"; exp_continue }
-gl "*?assword:*" { send "$password\r" }
}
}
')
我不知道,如果当你重定向输出产卵这将工作:我担心,预计将在什么都没有的工作。如果这也不行,删除“> /home/log_$ip 2>/dev/null &
”或使用
spawn ssh $ip tail -n 20 $location 2>/dev/null | tee /home/log_$ip
利于让一个后台,你可能不得不这样做(未经测试)
expect -c '...' > /home/log_$ip 2>&1 &
expect_pid=$!
# ...
# later
wait $expect_pid
VAR=$(< /home/log_$ip)
do something with "$VAR"
这看起来不错,我实际上使用尾巴-f,我希望它在后台运行,所以我添加&到你的线路spawn ssh $ ip tail -f $ location 2>/dev/null | tee/home/log_ $ ip,但它不起作用。 – user2864207
如果我只能在后台运行该命令,则您的答案非常有用。 – user2864207
您可以在后台启动整个expect程序,但是$ VAR不会捕获任何内容。 –
可以请人帮我做尾巴-f在后台运行 – user2864207