常用expect 脚本

来源:互联网 发布:易语言仓库管理源码 编辑:程序博客网 时间:2024/06/01 16:57

服务器多了之后, 就没办法登陆每台机器做管理. 一般的做法是用agent 程序部署在每个节点上, 用于数据采集和执行命令. 简单的做法是用expect 脚本, 模拟登陆每台机器执行命令. 常用的expect 脚本如下:

自动登陆机器: ./ssht.sh host_ip

#!/bin/bashcd $(dirname $0)host_ip=$1 # 要登陆的机器ipusername="username" # 一个集群中的机器通常有统一的用户名和密码, 所以直接写在脚本里了password="password" # 要经常更换密码以确保安全性expect -c "spawn ssh -o StrictHostKeyChecking=no -p 22 -l $username $host_ipexpect \"*assword: \"send \"$password\n\"interact"

在远程机器执行单个命令: ./send_remote_cmd.sh host_ip “command”

#!/bin/bashcd $(dirname $0)host=$1cmd=$2user="username"pswd="password"expect -c "set timeout 600spawn ssh -o StrictHostKeyChecking=no -p 22 -l $user $hostexpect -nocase \"*assword: \"send \"$pswd\n\"sleep 0.1send \"$cmd\n\"sleep 0.1send \"exit\n\"expect eof" | tr -d '\r' # expect 脚本返回结果里面是 \r\n, 是windows的行结束符, Linux 只有\n, 所以删掉\rexit 0

在远程机器执行多个命令: ./send_remote_multi_cmd.exp host_ip $PWD/command_file

#!/usr/bin/expectset host [lindex $argv 0]set cmd_file [lindex $argv 1]set user "username"set pswd "password"set multi_cmd [open $cmd_file r]set timeout 600spawn ssh -o StrictHostKeyChecking=no -p 36000 -l $user $hostexpect -nocase "*assword: "send "$pswd\n"sleep 0.1while {1} {    set cmd_line [gets $multi_cmd]        if {[eof $multi_cmd]} {            close $multi_cmd            break        }    puts "$cmd_line "    send "$cmd_line \n"    sleep 0.1}send "exit\n"expect eof

这个脚本可以预先在command_file 里面写好多条命令, 然后在远程机器上依次执行. 注意美元符号($)和双引号(“)都要反斜线()转义

拷贝文件到远程机器: ./scp_local_remote.sh host_ip local_file remote_dir

#!/bin/bashcd $(dirname $0)host_ip=$1src_file=$2remote_dir=$3username="username"password="password"expect -c "set timeout -1spawn scp  -o StrictHostKeyChecking=no -r ${src_file} ${username}@${host_ip}:${remote_dir}expect \"*assword: \"  send \"${password}\n\"expect \"100%\"expect eof" | tr -d '\r'

从远程机器拉文件也是一样.