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

expect写脚本

时间:2018-03-18 12:06:04      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:expect

expect写脚本

~/.ssh/know_hosts文件 [远程ip:公钥]

当我们使用公钥去ssh连接一台远程主机时,系统默认会把访问过的主机的公钥都记录在 ~/.ssh/know_hosts

cat ~/.ssh/known_hosts
192.168.221.20 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHzi7l7PDXCUwFW6Xy6Ipg7FwTwHT9oiEfpHSqTTm1pBc0abAGgBjh8KwqkhmP+Au4D4+1k8XiZGvo0TYhSTi+c=

expect远程登录另外一台机器

yum install expect -y
vim /usr/local/sbin/expect/expect-login.sh
#! /usr/bin/expect    //注意与“#!/bin/bash”区分开来
set host "192.168.221.20"   //设置2个变量host,passwd
set passwd "root"
spawn ssh root@$host      
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
interact   //停留在远程机器上不退出来  expect eof  停留在远程机器上一会儿再退出

chmod +x /usr/local/sbin/expect/expect-login.sh
[root@localhost expect]# ./expect-login.sh   //特别注意不能用bash去执行
spawn ssh root@192.168.221.20
root@192.168.221.20‘s password: 
Last login: Sun Mar 18 10:33:33 2018 from 192.168.221.10
[root@apenglinux-002 ~]#

expect远程登录另外一台机器并执行命令

vim expect-login-exec.sh 
#! /usr/bin/expect
set host "192.168.221.20"
set passwd "root"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"
send "touch /tmp/expect.txt\r"
expect "]*"
send "echo expect > /tmp/expect.txt\r"
expect "]*"
send "exit\r"

[root@localhost expect]# chmod +x expect-login-exec.sh 
[root@localhost expect]# ./expect-login-exec.sh 
spawn ssh root@192.168.221.20
root@192.168.221.20‘s password: 
Last login: Sun Mar 18 11:14:46 2018 from 192.168.221.10
[root@apenglinux-002 ~]# touch /tmp/expect.txt
[root@apenglinux-002 ~]# echo expect > /tmp/expect.txt
[root@apenglinux-002 ~]# [root@localhost expect]

expect写脚本

标签:expect

原文地址:http://blog.51cto.com/13480443/2088099

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