實驗:
linux本機(192.168.99.11)登陸遠程機器(192.168.99.77);
執行如下操作:
1)useradd yanes
2)mkdir /opt/test
3) exit自動退出
#!/bin/bash
passwd='123456'
/usr/local/bin/expect <<-EOF
set time 30
spawn ssh -p22 [email protected]
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect "*#"
send "useradd yanes\r"
expect "*#"
send "mkdir /opt/test\r"
expect "*#"
send "exit\r"
interact
expect eof
EOF
執行結果:
[root@localhost ~]# vi test-ssh.sh
#!/bin/bash
passwd='123456'
/usr/local/bin/expect <<-EOF
set time 30
spawn ssh -p22 [email protected]
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect "*#"
send "useradd yanes\r"
expect "*#"
send "mkdir /opt/test\r"
expect "*#"
send "exit\r"
interact
expect eof
EOF
[root@localhost ~]# sh test-ssh.sh
spawn ssh -p22 [email protected]
The authenticity of host '192.168.1.77 (192.168.1.77)' can't be established.
RSA key fingerprint is 5a:b0:56:4d:8f:d7:81:ae:c7:fc:d1:3e:5f:e4:21:b8.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.77' (RSA) to the list of known hosts.
[email protected]'s password:
Last login: Wed Dec 21 23:24:42 2016
[root@oracle11g ~]# useradd yanes
useradd: user yanes exists
[root@oracle11g ~]# mkdir /opt/test
[root@oracle11g ~]# [root@localhost ~]#
實驗結果成功;
實驗文檔見網盤:
http://pan.baidu.com/s/1c7V0CI
如果需要安裝expect工具和gcc工具,本人的其它兩篇博客(寫本文的時候,另外兩篇博客還未審覈通過)