码迷,mamicode.com
首页 > 其他好文 > 详细

expect 远程访问机器并执行命令

时间:2020-11-13 12:08:28      阅读:7      评论:0      收藏:0      [点我收藏+]

标签:new   需要   tin   print   mod   otp   roo   远程   lang   

有时我们需要批量登录远程机器,切换用户后,执行相关命令,如果一台一台登录执行,效率太低,可以考虑使用expect 脚本

代码如下:

#!/bin/bash
LANG=en
user="lv"

command1="touch a.txt"
command2="chmod 777 a.txt"
command3="cp a.txt b.txt"

for line in `cat ip.list`;do

ip=`echo $line |awk -F "," ‘{print $1}‘`
common_passwd=`echo $line |awk -F "," ‘{print $2}‘`
new_rootpasswd=`echo $line |awk -F "," ‘{print $3}‘` 

/usr/bin/expect << EOF
set time 30
spawn ssh $user@$ip

expect {
"yes/no" { send "yes\r";exp_continue}
"password:" { send "$common_passwd\r"}
}

expect "]*"
send "su -\r"

expect {
"Password:" { send "$new_rootpasswd\r"}
}
expect "]*"
send "$command1\r"
expect "]*"
send "$command2\r"
expect "]*" 
send "$command3\r"

expect "]*"
send "exit\r"
EOF

done

ip.list 文本内容如下:

192.168.245.129,zhou2,Lg2=0.301!@#,
192.168.245.130,zhou3,e=2.71828!@#,

脚本执行结果如下:
spawn ssh lv@192.168.245.129
lv@192.168.245.129‘s password:
Last login: Sun Nov 1 15:24:34 2020 from zhou1
[lv@zhou2 ~]$ su -
Password:
Last login: Sun Nov 1 15:28:18 CST 2020 on pts/1
[root@zhou2 ~]# touch a.txt
[root@zhou2 ~]# chmod 777 a.txt
[root@zhou2 ~]# cp a.txt b.txt
[root@zhou2 ~]# spawn ssh lv@192.168.245.130
lv@192.168.245.130‘s password:
Last login: Sun Nov 1 15:29:36 2020 from 192.168.245.1
[lv@zhou3 ~]$ su -
Password:
Last login: Sun Nov 1 15:29:50 CST 2020 on pts/0
[root@zhou3 ~]# touch a.txt
[root@zhou3 ~]# chmod 777 a.txt
[root@zhou3 ~]# cp a.txt b.txt
[root@zhou3 ~]# [lv@zhou1 ~]$

expect 远程访问机器并执行命令

标签:new   需要   tin   print   mod   otp   roo   远程   lang   

原文地址:https://blog.51cto.com/12606610/2545911

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!