Linux

王朝学院·作者佚名  2016-05-26
窄屏简体版  字體: |||超大  

linux - expect自动化远程登录脚本简单模式:

#!/usr/bin/expect -f set timeout 5 spawn ssh root@192.168.0.1expect "*assWord*" send "root\r" expect "#" send "ifconfig \r" expect eof

讲解:

send:用于向进程发送字符串expect:从进程接收字符串 比如:expect "*assword*"spawn:启动新的进程interact:允许用户交互怎么使用变量:

#!/usr/bin/expect -fset port 22set user rootset host 192.168.0.12set password rootset timeout -1spawn ssh -D $port $user@$host "ifconfig"expect { "*yes/no" { send "yes\r"; exp_continue} "*assword:" { send "$password\r" } } expect "*#*" send "ifconfig > /home/cfg \r"send "exit\r"}

讲解:

expect { "*yes/no" { send "yes\r"; exp_continue} "*assword:" { send "$password\r" } } 选择模式,exp_continue表示继续。通过读取配置文件获取变量:配置文件

192.168.0.1 root192.168.0.2 root

自动化登录脚本

#!/usr/bin/expect -fset f [open ./ip r] while { [gets $f line ]>=0 } { set ip [lindex $line 0] set pwd [lindex $line 1]spawn ssh $ipexpect "*password:" { send "$pwd\r" }expect "#"send "ifconfig \r"send "exit\r"interact}

讲解:

可以多台服务器循环执行,是个非常使用的方式!

自动化远程拷贝文件:

#!/usr/bin/expect -fset port 22set user rootset host 192.168.28.30set password rootset timeout -1spawn scp $host:/home/cfg ./expect {"*yes/no" { send "yes\r"; exp_continue}"*assword:" { send "$password\r" }}expect eof

讲解:

原理和ssh一样

远程执行命令后写入文件,再通过scp到本机服务器:

#!/usr/bin/expect -fset port 22set user rootset host 192.168.28.30set password rootset timeout -1spawn ssh -D $port $user@$host "ifconfig"expect {"*yes/no" { send "yes\r"; exp_continue}"*assword:" { send "$password\r" }}expect "*#*"send "ifconfig > /home/cfg \r"send "exit\r"interactspawn scp $host:/home/cfg ./expect {"*yes/no" { send "yes\r"; exp_continue}"*assword:" { send "$password\r" }}expect eof

讲解:

自动化运维,远程交互从服务器A上ssh到服务器B上,然后执行服务器B上的命令。http://www.cnblogs.com/javame/p/4272440.html

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航