小编典典

使用bash脚本自动化telnet会话

linux

我正在使用Bash脚本来自动化一些与telnet相关的任务。一旦自动化,用户与telnet之间将不会进行任何交互。(这将是完全自动化的)

脚本看起来像这样:

# execute some commands on the local system
# access a remote system with an IP address: 10.1.1.1 (for example)

telnet 10.1.1.1

# execute some commands on the remote system
# log all the activity (in a file) on the Local system
# exit telnet
# continue on with executing the rest of the script.

我在这里面临2个问题:

  1. 如何从脚本(无需人工干预)在远程系统上执行命令?

根据我对一些测试代码的经验,我可以推断出在执行 telnet 10.1.1.1
时,telnet进入了一个交互式会话,并且脚本中的后续代码行在本地系统上执行。如何在远程系统而不是本地系统上运行代码行?

  1. 我无法在本地系统的telnet会话中获得有关该活动的日志文件。我使用的stdout重定向在远程系统上进行复制(我不想执行复制操作以将日志复制到本地系统)。如何实现此功能?

阅读 606

收藏
2020-06-02

共1个答案

小编典典

编写expect脚本。

这是一个例子:

#!/usr/bin/expect

#If it all goes pear shaped the script will timeout after 20 seconds.
set timeout 20
#First argument is assigned to the variable name
set name [lindex $argv 0]
#Second argument is assigned to the variable user
set user [lindex $argv 1]
#Third argument is assigned to the variable password
set password [lindex $argv 2]
#This spawns the telnet program and connects it to the variable name
spawn telnet $name 
#The script expects login
expect "login:" 
#The script sends the user variable
send "$user "
#The script expects Password
expect "Password:"
#The script sends the password variable
send "$password "
#This hands control of the keyboard over to you (Nice expect feature!)
interact

跑步:

./myscript.expect name user password
2020-06-02