expect脚本获取远程服务器时间 time.sh
#!/usr/bin/expect
set timeout 15
set cmd_prompt "]#|~]?"
spawn ssh root@192.168.2.1
expect "password*"
send "密码\r"
set output [open datetime.now "w"]
expect -re $cmd_prompt {
send "date '+%Y%m%d %T'"
send "\r"
expect -re "\r\n(.*)\r\n(.*)"
set outcome $expect_out(1,string)
puts $output $outcome
}
send "exit"
send "\r"
expect EOF
执行脚本 run.sh
#!/bin/bash
./time.sh
linuxTime=`cat datetime.now`
echo "获取到时间: ${linuxTime}"
date -s "${linuxTime}"
两个脚本放到同一个目录下,执行run.sh
本文介绍了一个使用expect脚本通过SSH连接到远程Linux服务器并获取当前时间的流程。脚本中包含了设置超时时间、发送密码、接收命令提示符、执行date命令以及保存和打印时间信息的过程。在另一个run.sh脚本中,它调用time.sh并存储返回的时间,然后更新本地系统的日期。
1437

被折叠的 条评论
为什么被折叠?



