expect实现免交互执行命令

1、创建lucy用户,查看/etc/hosts内容

#!/usr/bin/expect
set ip [lindex $argv 0]
set user root
set password redhat
set timeout 5

spawn ssh $user@$ip
expect "yes/no" { send "yes\r"; exp_continue }
expect "password:" { send "$password\r" }

expect "#"
send "useradd lucy\r"
send "cat hosts\r"
send "exit\r"
expect eof

 

2、多个机器添加用户tom100方法一:

#!/bin/bash
while read LINES
do
        user=`echo $LINES |cut -d ' ' -f1`
        password=`echo $LINES |cut -d ' ' -f2`
        host=`echo $LINES |cut -d ' ' -f3`
        expect <<EOF
        spawn ssh $user@$host
        expect "yes/no"  {send "yes\r"}
        expect "password:" {send "$password\r"}
        expect "#" {send "useradd tom100\r"}
        send "exit\r"
        expect eof
EOF
done <ip.txt

 3、多个机器添加用户tom100方法二:

#!/bin/bash
while read user pass ip
do
        expect <<EOF
        spawn ssh $user@$ip
        expect "yes/no"  {send "yes\r"}
        expect "password:" {send "$pass\r"}
        expect "#" {send "useradd tom100\r"}
        send "exit\r"
        expect eof
EOF
done <ip.txt

4、ip.txt的格式

root redhat 192.168.101.20
root redhat 192.168.101.21
root redhat 192.168.101.22
posted @ 2020-04-21 14:17  汝南  阅读(152)  评论(0)    收藏  举报