ssh - 通过 ssh 和 cron(sshpass、expect 或其他解决方案)自动重启 ip-phone
问题描述
任务是每晚远程重启 ip-phones。
sshpass:
sshpass -p 12345678 ssh -o StrictHostKeyChecking=no admin@192.168.2.1 reboot
响应:远程主机关闭到 192.168.2.1 的连接。
此外,电话像往常一样在 CLI 中要求回答y。
预计:
COMM="
log_file debug.log
exp_internal 1
set timeout 5
spawn ssh admin@192.168.2.1
expect \"password:\"
send \"12345678\r\"
sleep 5
expect \"*>\"
send \"reboot\r\"
sleep 5
expect \"*y/N*\"
send \"y\r\"
expect eof
"
expect -c "$COMM"
当我自己从控制台执行此操作时,一切正常。使用cron,在 debug.log 中,由于某种原因,在设备上授权后,expect \"*>\"
没有出现输入命令的行。即使我们删除expect \"*>\"
并只使用send,也没有任何反应。
我寻求解决问题的提示或提出其他解决方案。谢谢。
控制台和 cron控制台之间的debug.log不同:
expect: does " \r\n" (spawn_id exp5) match glob pattern "*>"? no
^[[1;36m
expect: does " \r\n\u001b[1;36m\r\n\t" (spawn_id exp5) match glob pattern "*>"? no
Grandstream GXV3240 Command-Line Interface Copyright 2017
Grandstream Networks, Inc.
^[[0m
GXV3240>
expect: does " \r\n\u001b[1;36m\r\n\tGrandstream GXV3240 Command-Line Interface Copyright 2017\r\n\t\tGrandstream Networks, Inc.\r\n\u001b[0m\r\nGXV3240> " (spawn_id exp5) match glob pattern "*>"? yes
expect: set expect_out(0,string) " \r\n\u001b[1;36m\r\n\tGrandstream GXV3240 Command-Line Interface Copyright 2017\r\n\t\tGrandstream Networks, Inc.\r\n\u001b[0m\r\nGXV3240>"
expect: set expect_out(spawn_id) "exp5"
expect: set expect_out(buffer) " \r\n\u001b[1;36m\r\n\tGrandstream GXV3240 Command-Line Interface Copyright 2017\r\n\t\tGrandstream Networks, Inc.\r\n\u001b[0m\r\nGXV3240>"
send: sending "reboot\r" to { exp5 }
计划:
expect: does " " (spawn_id exp4) match glob pattern "*>"? no
^[[1;36m
Grandstream GXV3240 Command-Line Interface Copyright 2017
Grandstream Networks, Inc.
^[[0m
^[[6n
expect: does " \r\n\u001b[1;36m\r\n\tGrandstream GXV3240 Command-Line Interface Copyright 2017\r\n\t\tGrandstream Networks, Inc.\r\n\u001b[0m\r\n\u001b[6n" (spawn_id exp4) match glob pattern "*>"? no
expect: timed out
send: sending "reboot\r" to { exp4 }
expect: does " \r\n\u001b[1;36m\r\n\tGrandstream GXV3240 Command-Line Interface Copyright 2017\r\n\t\tGrandstream Networks, Inc.\r\n\u001b[0m\r\n\u001b[6n" (spawn_id exp4) match glob pattern "*y/N*"? no
expect: timed out
解决方案
我不知道这是否能解决您的问题:没有看到调试输出就不可能说。
当您将期望代码嵌入到 shell 脚本中时,我建议使用 heredoc——这使得引用更加简单
expect <<'END_EXPECT'
log_file debug.log
exp_internal 1
set timeout 10
spawn ssh admin@192.168.2.1
expect "password:"
send "12345678\r"
expect "*>"
send "reboot\r"
expect "y/N"
send "y\r"
expect eof
END_EXPECT
我增加了超时并删除了睡眠——如果你有正确的模式,通常在期望脚本中不需要睡眠。
推荐阅读
- c++ - static_assert 与带有自定义分配器的 std::vector 一起失败
- .net - 无法使用 NLog 登录到数据库
- c - 这是在中型项目中实现封装的有效 OOP 替代方案吗?
- google-cloud-platform - GCP Google Cloud Storage:避免昂贵的数据传出网络出口
- java - java.util.Collections#copy 方法在 kotlin 中的外观如何?
- api - 我应该使用 OAuth 让 SPA 与后端通信吗?
- java - 如何在开头将标题设置为 PDF 以及如何设置居中对齐
- android - Firebase ML 智能回复支持哪些语言?
- python - Selenium 滚动到页面底部偶尔会停止
- kotest - 在类级别或容器级别设置标签