Ubuntu下使用SecureCRT进行批量操作的实现方法
.vbs(VBScript)或.py(Python)脚本文件(包含创建会话的命令)。SessionName(会话名称)、HostName(主机地址)、UserName(用户名)等参数,生成多个批量会话脚本。expect工具(Ubuntu终端执行sudo apt-get install expect)。setup_securecrt.exp脚本,内容如下(替换$session_name、$host、$user、$password为变量):#!/usr/bin/expect -f
set timeout -1
set session_name [lindex $argv 0]
set host [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]
spawn securecrt
expect "SecureCRT"
send "file new-session\r"
expect "Session name:"
send "$session_name\r"
expect "Connection type:"
send "SSH2\r"
expect "Host name or IP address:"
send "$host\r"
expect "Port:"
send "22\r"
expect "User name:"
send "$user\r"
expect "Password:"
send "$password\r"
expect eof
chmod +x setup_securecrt.exp。./setup_securecrt.exp "Session1" "192.168.1.101" "user1" "pass1"
./setup_securecrt.exp "Session2" "192.168.1.102" "user2" "pass2"
./setup_securecrt.exp "Session3" "192.168.1.103" "user3" "pass3"
此方法可通过循环语句(如Shell的for循环)扩展,实现大规模批量创建。VBScript示例:编写脚本自动登录并批量执行命令(如ls -l、df -h):
crt.Screen.Send "username" & Chr(13) ' 发送用户名并回车
crt.Screen.WaitForString "Password:" ' 等待密码提示
crt.Screen.Send "password" & Chr(13) ' 发送密码并回车
crt.Screen.WaitForString "#" ' 等待命令提示符(根据实际提示符调整)
' 批量执行命令
Dim commands
commands = Array("ls -l", "df -h", "uptime") ' 定义命令数组
For Each cmd In commands
crt.Screen.Send cmd & Chr(13) ' 发送命令
crt.Screen.WaitForString "#" ' 等待命令执行完成
crt.Screen.Print crt.Screen.ReadString("#") ' 打印命令输出
Next
保存为.vbs文件,在SecureCRT中“运行脚本”即可批量执行。
Python示例:使用SecureCRT的Python API实现更灵活的批量操作:
import SecureCRT
crt = SecureCRT.Session()
# 连接远程设备
crt.Connect("/SSH2 192.168.1.101")
crt.Login("user1", "pass1")
crt.WaitForString("#")
# 批量执行命令
commands = ["ls -l", "df -h", "uptime"]
for cmd in commands:
crt.Send(cmd + "\r")
crt.WaitForString("#")
print(crt.Screen.ReadString("#")) # 输出命令结果
crt.Disconnect()
batch_exec.sh,通过securecrt命令批量连接服务器并执行命令:#!/bin/bash
# 定义服务器列表(IP、用户名、密码)
servers=(
"192.168.1.101 user1 pass1"
"192.168.1.102 user2 pass2"
"192.168.1.103 user3 pass3"
)
# 循环连接每个服务器并执行命令
for server in "${servers[@]}"; do
ip=$(echo $server | awk '{print $1}')
user=$(echo $server | awk '{print $2}')
pass=$(echo $server | awk '{print $3}')
echo "Connecting to $ip..."
securecrt -q -L $user,$pass $ip << EOF
ls -l
df -h
uptime
exit
EOF done
保存后赋予执行权限:`chmod +x batch_exec.sh`,运行`./batch_exec.sh`即可批量执行命令。
### 三、注意事项
- **安全性**:避免在脚本中明文存储密码,建议使用SSH密钥认证(需提前配置公钥到远程服务器)。
- **错误处理**:在脚本中添加`WaitForString`等待关键提示符(如`#`、`$`),避免命令未执行完成就继续下一步。
- **兼容性**:SecureCRT的脚本功能主要针对Windows设计,Ubuntu下需通过Wine安装或使用替代工具(如内置`ssh`命令、`paramiko`库),确保脚本兼容性。